Update app.py
Browse files
app.py
CHANGED
|
@@ -3,9 +3,9 @@ import gradio as gr
|
|
| 3 |
import requests
|
| 4 |
import inspect
|
| 5 |
import pandas as pd
|
| 6 |
-
from smolagents import CodeAgent, DuckDuckGoSearchTool,
|
| 7 |
-
|
| 8 |
# (Keep Constants and BasicAgent class as is)
|
|
|
|
| 9 |
# --- Constants ---
|
| 10 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 11 |
|
|
@@ -13,8 +13,8 @@ DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
|
| 13 |
class BasicAgent:
|
| 14 |
def __init__(self):
|
| 15 |
print("BasicAgent initialized.")
|
| 16 |
-
self.agent = CodeAgent(tools=[DuckDuckGoSearchTool()], model=HfApiModel())
|
| 17 |
-
|
| 18 |
SYSTEM_PROMPT = """You are a general AI assistant. I will ask you a question. Report your thoughts, and
|
| 19 |
finish your answer with the following template: FINAL ANSWER: [YOUR FINAL ANSWER].
|
| 20 |
YOUR FINAL ANSWER should be a number OR as few words as possible OR a comma separated
|
|
@@ -27,7 +27,7 @@ class BasicAgent:
|
|
| 27 |
to be put in the list is a number or a string.
|
| 28 |
"""
|
| 29 |
self.agent.prompt_templates["system_prompt"] = self.agent.prompt_templates["system_prompt"] + SYSTEM_PROMPT
|
| 30 |
-
|
| 31 |
def __call__(self, question: str) -> str:
|
| 32 |
print(f"Agent received question (first 50 chars): {question[:50]}...")
|
| 33 |
final_answer = self.agent.run(question)
|
|
@@ -41,7 +41,6 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
| 41 |
"""
|
| 42 |
# --- Determine HF Space Runtime URL and Repo URL ---
|
| 43 |
space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
|
| 44 |
-
|
| 45 |
if profile:
|
| 46 |
username= f"{profile.username}"
|
| 47 |
print(f"User logged in: {username}")
|
|
@@ -59,6 +58,7 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
| 59 |
except Exception as e:
|
| 60 |
print(f"Error instantiating agent: {e}")
|
| 61 |
return f"Error initializing agent: {e}", None
|
|
|
|
| 62 |
# 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)
|
| 63 |
agent_code = f"https://huggingface.co/spaces/ghanemfaouri/Final_Assignment_Template/tree/main"
|
| 64 |
print(agent_code)
|
|
@@ -106,7 +106,7 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
| 106 |
print("Agent did not produce any answers to submit.")
|
| 107 |
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
| 108 |
|
| 109 |
-
# 4. Prepare Submission
|
| 110 |
submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
|
| 111 |
status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
|
| 112 |
print(status_update)
|
|
@@ -154,7 +154,6 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
| 154 |
results_df = pd.DataFrame(results_log)
|
| 155 |
return status_message, results_df
|
| 156 |
|
| 157 |
-
|
| 158 |
# --- Build Gradio Interface using Blocks ---
|
| 159 |
with gr.Blocks() as demo:
|
| 160 |
gr.Markdown("# Basic Agent Evaluation Runner")
|
|
@@ -163,15 +162,11 @@ with gr.Blocks() as demo:
|
|
| 163 |
"Log in to your Hugging Face account using the button below. This uses your HF username for submission. "
|
| 164 |
"Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score."
|
| 165 |
)
|
| 166 |
-
|
| 167 |
gr.LoginButton()
|
| 168 |
-
|
| 169 |
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
| 170 |
-
|
| 171 |
status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
|
| 172 |
# Removed max_rows=10 from DataFrame constructor
|
| 173 |
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
| 174 |
-
|
| 175 |
run_button.click(
|
| 176 |
fn=run_and_submit_all,
|
| 177 |
outputs=[status_output, results_table]
|
|
@@ -182,21 +177,17 @@ if __name__ == "__main__":
|
|
| 182 |
# Check for SPACE_HOST and SPACE_ID at startup for information
|
| 183 |
space_host_startup = os.getenv("SPACE_HOST")
|
| 184 |
space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
|
| 185 |
-
|
| 186 |
if space_host_startup:
|
| 187 |
print(f"✅ SPACE_HOST found: {space_host_startup}")
|
| 188 |
print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
|
| 189 |
else:
|
| 190 |
print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
|
| 191 |
-
|
| 192 |
if space_id_startup: # Print repo URLs if SPACE_ID is found
|
| 193 |
print(f"✅ SPACE_ID found: {space_id_startup}")
|
| 194 |
print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
|
| 195 |
print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
|
| 196 |
else:
|
| 197 |
print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
|
| 198 |
-
|
| 199 |
print("-"*(60 + len(" App Starting ")) + "\n")
|
| 200 |
-
|
| 201 |
print("Launching Gradio Interface for Basic Agent Evaluation...")
|
| 202 |
demo.launch(debug=True, share=False)
|
|
|
|
| 3 |
import requests
|
| 4 |
import inspect
|
| 5 |
import pandas as pd
|
| 6 |
+
from smolagents import CodeAgent, DuckDuckGoSearchTool, InferenceClientModel # <--- CHANGE THIS LINE
|
|
|
|
| 7 |
# (Keep Constants and BasicAgent class as is)
|
| 8 |
+
|
| 9 |
# --- Constants ---
|
| 10 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 11 |
|
|
|
|
| 13 |
class BasicAgent:
|
| 14 |
def __init__(self):
|
| 15 |
print("BasicAgent initialized.")
|
| 16 |
+
# self.agent = CodeAgent(tools=[DuckDuckGoSearchTool()], model=HfApiModel()) # <--- OLD LINE
|
| 17 |
+
self.agent = CodeAgent(tools=[DuckDuckGoSearchTool()], model=InferenceClientModel()) # <--- CHANGE THIS LINE
|
| 18 |
SYSTEM_PROMPT = """You are a general AI assistant. I will ask you a question. Report your thoughts, and
|
| 19 |
finish your answer with the following template: FINAL ANSWER: [YOUR FINAL ANSWER].
|
| 20 |
YOUR FINAL ANSWER should be a number OR as few words as possible OR a comma separated
|
|
|
|
| 27 |
to be put in the list is a number or a string.
|
| 28 |
"""
|
| 29 |
self.agent.prompt_templates["system_prompt"] = self.agent.prompt_templates["system_prompt"] + SYSTEM_PROMPT
|
| 30 |
+
|
| 31 |
def __call__(self, question: str) -> str:
|
| 32 |
print(f"Agent received question (first 50 chars): {question[:50]}...")
|
| 33 |
final_answer = self.agent.run(question)
|
|
|
|
| 41 |
"""
|
| 42 |
# --- Determine HF Space Runtime URL and Repo URL ---
|
| 43 |
space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
|
|
|
|
| 44 |
if profile:
|
| 45 |
username= f"{profile.username}"
|
| 46 |
print(f"User logged in: {username}")
|
|
|
|
| 58 |
except Exception as e:
|
| 59 |
print(f"Error instantiating agent: {e}")
|
| 60 |
return f"Error initializing agent: {e}", None
|
| 61 |
+
|
| 62 |
# 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)
|
| 63 |
agent_code = f"https://huggingface.co/spaces/ghanemfaouri/Final_Assignment_Template/tree/main"
|
| 64 |
print(agent_code)
|
|
|
|
| 106 |
print("Agent did not produce any answers to submit.")
|
| 107 |
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
| 108 |
|
| 109 |
+
# 4. Prepare Submission
|
| 110 |
submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
|
| 111 |
status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
|
| 112 |
print(status_update)
|
|
|
|
| 154 |
results_df = pd.DataFrame(results_log)
|
| 155 |
return status_message, results_df
|
| 156 |
|
|
|
|
| 157 |
# --- Build Gradio Interface using Blocks ---
|
| 158 |
with gr.Blocks() as demo:
|
| 159 |
gr.Markdown("# Basic Agent Evaluation Runner")
|
|
|
|
| 162 |
"Log in to your Hugging Face account using the button below. This uses your HF username for submission. "
|
| 163 |
"Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score."
|
| 164 |
)
|
|
|
|
| 165 |
gr.LoginButton()
|
|
|
|
| 166 |
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
|
|
|
| 167 |
status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
|
| 168 |
# Removed max_rows=10 from DataFrame constructor
|
| 169 |
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
|
|
|
| 170 |
run_button.click(
|
| 171 |
fn=run_and_submit_all,
|
| 172 |
outputs=[status_output, results_table]
|
|
|
|
| 177 |
# Check for SPACE_HOST and SPACE_ID at startup for information
|
| 178 |
space_host_startup = os.getenv("SPACE_HOST")
|
| 179 |
space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
|
|
|
|
| 180 |
if space_host_startup:
|
| 181 |
print(f"✅ SPACE_HOST found: {space_host_startup}")
|
| 182 |
print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
|
| 183 |
else:
|
| 184 |
print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
|
|
|
|
| 185 |
if space_id_startup: # Print repo URLs if SPACE_ID is found
|
| 186 |
print(f"✅ SPACE_ID found: {space_id_startup}")
|
| 187 |
print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
|
| 188 |
print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
|
| 189 |
else:
|
| 190 |
print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
|
|
|
|
| 191 |
print("-"*(60 + len(" App Starting ")) + "\n")
|
|
|
|
| 192 |
print("Launching Gradio Interface for Basic Agent Evaluation...")
|
| 193 |
demo.launch(debug=True, share=False)
|