Update app.py
Browse files
app.py
CHANGED
|
@@ -3,8 +3,7 @@ import gradio as gr
|
|
| 3 |
import requests
|
| 4 |
import inspect
|
| 5 |
import pandas as pd
|
| 6 |
-
from smolagents import CodeAgent, DuckDuckGoSearchTool, InferenceClientModel #
|
| 7 |
-
# (Keep Constants and BasicAgent class as is)
|
| 8 |
|
| 9 |
# --- Constants ---
|
| 10 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
|
@@ -13,18 +12,57 @@ DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
|
| 13 |
class BasicAgent:
|
| 14 |
def __init__(self):
|
| 15 |
print("BasicAgent initialized.")
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
"""
|
| 29 |
self.agent.prompt_templates["system_prompt"] = self.agent.prompt_templates["system_prompt"] + SYSTEM_PROMPT
|
| 30 |
|
|
@@ -60,8 +98,9 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
| 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 |
-
|
| 64 |
-
|
|
|
|
| 65 |
|
| 66 |
# 2. Fetch Questions
|
| 67 |
print(f"Fetching questions from: {questions_url}")
|
|
@@ -165,8 +204,8 @@ with gr.Blocks() as demo:
|
|
| 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]
|
|
@@ -174,15 +213,14 @@ with gr.Blocks() as demo:
|
|
| 174 |
|
| 175 |
if __name__ == "__main__":
|
| 176 |
print("\n" + "-"*30 + " App Starting " + "-"*30)
|
| 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")
|
| 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:
|
| 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")
|
|
|
|
| 3 |
import requests
|
| 4 |
import inspect
|
| 5 |
import pandas as pd
|
| 6 |
+
from smolagents import CodeAgent, DuckDuckGoSearchTool, InferenceClientModel # Make sure InferenceClientModel is imported
|
|
|
|
| 7 |
|
| 8 |
# --- Constants ---
|
| 9 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
|
|
|
| 12 |
class BasicAgent:
|
| 13 |
def __init__(self):
|
| 14 |
print("BasicAgent initialized.")
|
| 15 |
+
|
| 16 |
+
# --- CHOOSE THE BEST MODEL HERE ---
|
| 17 |
+
# Using Meta-Llama-3-8B-Instruct for a good balance of performance and cost.
|
| 18 |
+
# Ensure you have accepted its terms on Hugging Face and have sufficient
|
| 19 |
+
# Inference Provider credits or a PRO subscription with pay-as-you-go enabled.
|
| 20 |
+
self.agent = CodeAgent(
|
| 21 |
+
tools=[DuckDuckGoSearchTool()],
|
| 22 |
+
model=InferenceClientModel(model_id="meta-llama/Meta-Llama-3-8B-Instruct"),
|
| 23 |
+
max_steps=10, # Increase max_steps for more complex reasoning chains if needed
|
| 24 |
+
# use_structured_outputs_internally=True # Optional: Can sometimes improve performance for capable models, but might also cause issues if the model doesn't strictly adhere. Test this if needed.
|
| 25 |
+
)
|
| 26 |
+
|
| 27 |
+
# --- REFINED SYSTEM PROMPT ---
|
| 28 |
+
SYSTEM_PROMPT = """You are a highly capable and precise AI assistant. Your primary goal is to answer questions accurately and concisely, following strict formatting rules.
|
| 29 |
+
|
| 30 |
+
**Here's how you should approach each question:**
|
| 31 |
+
1. **Understand the Request:** Read the question carefully to identify what information is needed and what type of answer is expected (number, string, or list).
|
| 32 |
+
2. **Gather Information:**
|
| 33 |
+
* First, try to answer based on your internal knowledge if the information is common or involves simple logic/arithmetic.
|
| 34 |
+
* If the question requires factual knowledge, current information, or is complex, **you MUST use the `DuckDuckGoSearchTool`**. Formulate precise search queries to get the most relevant results.
|
| 35 |
+
* Analyze the search results meticulously to extract the exact information required.
|
| 36 |
+
3. **Reason Step-by-Step:** Before providing the final answer, explicitly state your thought process. This helps in complex reasoning. Use a "Thought:" section.
|
| 37 |
+
4. **Formulate FINAL ANSWER:** Construct your final answer strictly according to these rules:
|
| 38 |
+
* **Template:** Always end your entire response with `FINAL ANSWER: [YOUR FINAL ANSWER]`.
|
| 39 |
+
* **Numbers:** If the answer is a number, write it in digits ONLY, without commas, unit symbols (e.g., "$", "%", "km", "kg"), or text (e.g., "one" instead of "1"). For example, "12345" not "12,345" or "12345 dollars".
|
| 40 |
+
* **Strings (words):** If the answer is a string, use as few words as possible. Do NOT use articles (a, an, the). Do NOT use abbreviations. If a number is part of a string, write it in plain English words (e.g., "twenty" instead of "20"), unless it's a specific numerical value (like a year or an ID).
|
| 41 |
+
* **Comma-separated lists:** If the answer is a list, apply the above rules to each element in the list and separate elements with a comma and a single space (e.g., "apple, banana, orange" or "one, two, three").
|
| 42 |
+
|
| 43 |
+
**Examples of desired FINAL ANSWER formats:**
|
| 44 |
+
|
| 45 |
+
* **Question:** What is the capital of Japan?
|
| 46 |
+
* **Thought:** I know the capital of Japan is a specific city.
|
| 47 |
+
* **FINAL ANSWER: Tokyo**
|
| 48 |
+
|
| 49 |
+
* **Question:** How many days are in a common year?
|
| 50 |
+
* **Thought:** A common year has a fixed number of days.
|
| 51 |
+
* **FINAL ANSWER: three hundred sixty five**
|
| 52 |
+
|
| 53 |
+
* **Question:** Who developed Python and in what year?
|
| 54 |
+
* **Thought:** This requires factual recall of an inventor and a year. I will use DuckDuckGoSearchTool if uncertain.
|
| 55 |
+
* **FINAL ANSWER: Guido van Rossum, nineteen ninety one**
|
| 56 |
+
|
| 57 |
+
* **Question:** List three primary colors.
|
| 58 |
+
* **Thought:** I need to list common primary colors.
|
| 59 |
+
* **FINAL ANSWER: red, yellow, blue**
|
| 60 |
+
|
| 61 |
+
* **Question:** Calculate 15 multiplied by 7.
|
| 62 |
+
* **Thought:** This is a simple arithmetic calculation.
|
| 63 |
+
* **FINAL ANSWER: one hundred five**
|
| 64 |
+
|
| 65 |
+
Your detailed thought process (after "Thought:") should lead directly to the accurate `FINAL ANSWER` based on the specified format.
|
| 66 |
"""
|
| 67 |
self.agent.prompt_templates["system_prompt"] = self.agent.prompt_templates["system_prompt"] + SYSTEM_PROMPT
|
| 68 |
|
|
|
|
| 98 |
return f"Error initializing agent: {e}", None
|
| 99 |
|
| 100 |
# 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)
|
| 101 |
+
# IMPORTANT: Update this to YOUR SPACE_ID if you've cloned it!
|
| 102 |
+
agent_code = f"https://huggingface.co/spaces/{os.getenv('SPACE_ID', 'ghanemfaouri/Final_Assignment_Template')}/tree/main"
|
| 103 |
+
print(f"Agent code will link to: {agent_code}") # Added a print for clarity
|
| 104 |
|
| 105 |
# 2. Fetch Questions
|
| 106 |
print(f"Fetching questions from: {questions_url}")
|
|
|
|
| 204 |
gr.LoginButton()
|
| 205 |
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
| 206 |
status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
|
|
|
|
| 207 |
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
| 208 |
+
|
| 209 |
run_button.click(
|
| 210 |
fn=run_and_submit_all,
|
| 211 |
outputs=[status_output, results_table]
|
|
|
|
| 213 |
|
| 214 |
if __name__ == "__main__":
|
| 215 |
print("\n" + "-"*30 + " App Starting " + "-"*30)
|
|
|
|
| 216 |
space_host_startup = os.getenv("SPACE_HOST")
|
| 217 |
+
space_id_startup = os.getenv("SPACE_ID")
|
| 218 |
if space_host_startup:
|
| 219 |
print(f"✅ SPACE_HOST found: {space_host_startup}")
|
| 220 |
print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
|
| 221 |
else:
|
| 222 |
print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
|
| 223 |
+
if space_id_startup:
|
| 224 |
print(f"✅ SPACE_ID found: {space_id_startup}")
|
| 225 |
print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
|
| 226 |
print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
|