Update app.py
Browse files
app.py
CHANGED
|
@@ -3,32 +3,89 @@ import gradio as gr
|
|
| 3 |
import requests
|
| 4 |
import inspect
|
| 5 |
import pandas as pd
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
|
| 7 |
-
# (Keep Constants as is)
|
| 8 |
# --- Constants ---
|
| 9 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 10 |
|
| 11 |
-
# ---
|
| 12 |
-
#
|
| 13 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
def __init__(self):
|
| 15 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
def __call__(self, question: str) -> str:
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
|
| 22 |
-
def run_and_submit_all(
|
| 23 |
"""
|
| 24 |
-
Fetches all questions, runs the
|
| 25 |
and displays the results.
|
| 26 |
"""
|
| 27 |
# --- Determine HF Space Runtime URL and Repo URL ---
|
| 28 |
space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
|
| 29 |
|
| 30 |
if profile:
|
| 31 |
-
username= f"{profile.username}"
|
| 32 |
print(f"User logged in: {username}")
|
| 33 |
else:
|
| 34 |
print("User not logged in.")
|
|
@@ -38,13 +95,13 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
| 38 |
questions_url = f"{api_url}/questions"
|
| 39 |
submit_url = f"{api_url}/submit"
|
| 40 |
|
| 41 |
-
# 1. Instantiate Agent
|
| 42 |
try:
|
| 43 |
-
agent =
|
| 44 |
except Exception as e:
|
| 45 |
print(f"Error instantiating agent: {e}")
|
| 46 |
return f"Error initializing agent: {e}", None
|
| 47 |
-
|
| 48 |
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
| 49 |
print(agent_code)
|
| 50 |
|
|
@@ -139,22 +196,15 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
| 139 |
results_df = pd.DataFrame(results_log)
|
| 140 |
return status_message, results_df
|
| 141 |
|
| 142 |
-
|
| 143 |
# --- Build Gradio Interface using Blocks ---
|
| 144 |
with gr.Blocks() as demo:
|
| 145 |
-
gr.Markdown("#
|
| 146 |
gr.Markdown(
|
| 147 |
"""
|
| 148 |
**Instructions:**
|
| 149 |
-
|
| 150 |
-
1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
|
| 151 |
2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
|
| 152 |
3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
|
| 153 |
-
|
| 154 |
-
---
|
| 155 |
-
**Disclaimers:**
|
| 156 |
-
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).
|
| 157 |
-
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.
|
| 158 |
"""
|
| 159 |
)
|
| 160 |
|
|
@@ -163,7 +213,6 @@ with gr.Blocks() as demo:
|
|
| 163 |
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
| 164 |
|
| 165 |
status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
|
| 166 |
-
# Removed max_rows=10 from DataFrame constructor
|
| 167 |
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
| 168 |
|
| 169 |
run_button.click(
|
|
@@ -173,9 +222,8 @@ with gr.Blocks() as demo:
|
|
| 173 |
|
| 174 |
if __name__ == "__main__":
|
| 175 |
print("\n" + "-"*30 + " App Starting " + "-"*30)
|
| 176 |
-
# Check for SPACE_HOST and SPACE_ID at startup for information
|
| 177 |
space_host_startup = os.getenv("SPACE_HOST")
|
| 178 |
-
space_id_startup = os.getenv("SPACE_ID")
|
| 179 |
|
| 180 |
if space_host_startup:
|
| 181 |
print(f"✅ SPACE_HOST found: {space_host_startup}")
|
|
@@ -183,7 +231,7 @@ if __name__ == "__main__":
|
|
| 183 |
else:
|
| 184 |
print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
|
| 185 |
|
| 186 |
-
if space_id_startup:
|
| 187 |
print(f"✅ SPACE_ID found: {space_id_startup}")
|
| 188 |
print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
|
| 189 |
print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
|
|
@@ -192,5 +240,5 @@ if __name__ == "__main__":
|
|
| 192 |
|
| 193 |
print("-"*(60 + len(" App Starting ")) + "\n")
|
| 194 |
|
| 195 |
-
print("Launching Gradio Interface for
|
| 196 |
demo.launch(debug=True, share=False)
|
|
|
|
| 3 |
import requests
|
| 4 |
import inspect
|
| 5 |
import pandas as pd
|
| 6 |
+
from langchain.agents import AgentExecutor, create_react_agent
|
| 7 |
+
from langchain_google_genai import ChatGoogleGenerativeAI
|
| 8 |
+
from langchain_core.prompts import PromptTemplate
|
| 9 |
+
from langchain_community.tools import DuckDuckGoSearchRun # <-- IMPORTED DUCKDUCKGO
|
| 10 |
|
|
|
|
| 11 |
# --- Constants ---
|
| 12 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 13 |
|
| 14 |
+
# --- Tool Definition ---
|
| 15 |
+
# Replaced Google Search with DuckDuckGo. This tool doesn't require an API key.
|
| 16 |
+
search_tool = DuckDuckGoSearchRun()
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
# --- Agent Definition ---
|
| 20 |
+
class RealAgent:
|
| 21 |
def __init__(self):
|
| 22 |
+
# Initialize the language model
|
| 23 |
+
self.llm = ChatGoogleGenerativeAI(model="gemini-1.5-pro-latest", temperature=0)
|
| 24 |
+
|
| 25 |
+
# Define the prompt template
|
| 26 |
+
prompt_template = """
|
| 27 |
+
Answer the following questions as best you can. You have access to the following tools:
|
| 28 |
+
|
| 29 |
+
{tools}
|
| 30 |
+
|
| 31 |
+
Use the following format:
|
| 32 |
+
|
| 33 |
+
Question: the input question you must answer
|
| 34 |
+
Thought: you should always think about what to do
|
| 35 |
+
Action: the action to take, should be one of [{tool_names}]
|
| 36 |
+
Action Input: the input to the action
|
| 37 |
+
Observation: the result of the action
|
| 38 |
+
... (this Thought/Action/Action Input/Observation can repeat N times)
|
| 39 |
+
Thought: I now know the final answer
|
| 40 |
+
Final Answer: the final answer to the original input question
|
| 41 |
+
|
| 42 |
+
Begin!
|
| 43 |
+
|
| 44 |
+
Question: {input}
|
| 45 |
+
Thought:{agent_scratchpad}
|
| 46 |
+
"""
|
| 47 |
+
self.prompt = PromptTemplate.from_template(prompt_template)
|
| 48 |
+
|
| 49 |
+
# Define the tools - now using the DuckDuckGo tool
|
| 50 |
+
self.tools = [search_tool]
|
| 51 |
+
|
| 52 |
+
# Create the agent
|
| 53 |
+
self.agent = create_react_agent(
|
| 54 |
+
self.llm,
|
| 55 |
+
self.tools,
|
| 56 |
+
self.prompt,
|
| 57 |
+
)
|
| 58 |
+
|
| 59 |
+
# Create the agent executor
|
| 60 |
+
self.agent_executor = AgentExecutor(
|
| 61 |
+
agent=self.agent,
|
| 62 |
+
tools=self.tools,
|
| 63 |
+
verbose=True,
|
| 64 |
+
handle_parsing_errors=True,
|
| 65 |
+
max_iterations=10,
|
| 66 |
+
)
|
| 67 |
+
|
| 68 |
def __call__(self, question: str) -> str:
|
| 69 |
+
try:
|
| 70 |
+
# We must set the tool name explicitly in the invoke call for some versions of langchain
|
| 71 |
+
response = self.agent_executor.invoke({
|
| 72 |
+
"input": question,
|
| 73 |
+
"tool_names": ", ".join([t.name for t in self.tools])
|
| 74 |
+
})
|
| 75 |
+
return response.get("output", "No answer found.")
|
| 76 |
+
except Exception as e:
|
| 77 |
+
return f"Error invoking agent: {e}"
|
| 78 |
|
| 79 |
+
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
| 80 |
"""
|
| 81 |
+
Fetches all questions, runs the RealAgent on them, submits all answers,
|
| 82 |
and displays the results.
|
| 83 |
"""
|
| 84 |
# --- Determine HF Space Runtime URL and Repo URL ---
|
| 85 |
space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
|
| 86 |
|
| 87 |
if profile:
|
| 88 |
+
username = f"{profile.username}"
|
| 89 |
print(f"User logged in: {username}")
|
| 90 |
else:
|
| 91 |
print("User not logged in.")
|
|
|
|
| 95 |
questions_url = f"{api_url}/questions"
|
| 96 |
submit_url = f"{api_url}/submit"
|
| 97 |
|
| 98 |
+
# 1. Instantiate Agent
|
| 99 |
try:
|
| 100 |
+
agent = RealAgent()
|
| 101 |
except Exception as e:
|
| 102 |
print(f"Error instantiating agent: {e}")
|
| 103 |
return f"Error initializing agent: {e}", None
|
| 104 |
+
|
| 105 |
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
| 106 |
print(agent_code)
|
| 107 |
|
|
|
|
| 196 |
results_df = pd.DataFrame(results_log)
|
| 197 |
return status_message, results_df
|
| 198 |
|
|
|
|
| 199 |
# --- Build Gradio Interface using Blocks ---
|
| 200 |
with gr.Blocks() as demo:
|
| 201 |
+
gr.Markdown("# Real Agent Evaluation Runner (with DuckDuckGo)")
|
| 202 |
gr.Markdown(
|
| 203 |
"""
|
| 204 |
**Instructions:**
|
| 205 |
+
1. This space is a solution to the final assignment of the Hugging Face AI Agents course, using Gemini Pro and DuckDuckGo.
|
|
|
|
| 206 |
2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
|
| 207 |
3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 208 |
"""
|
| 209 |
)
|
| 210 |
|
|
|
|
| 213 |
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
| 214 |
|
| 215 |
status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
|
|
|
|
| 216 |
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
| 217 |
|
| 218 |
run_button.click(
|
|
|
|
| 222 |
|
| 223 |
if __name__ == "__main__":
|
| 224 |
print("\n" + "-"*30 + " App Starting " + "-"*30)
|
|
|
|
| 225 |
space_host_startup = os.getenv("SPACE_HOST")
|
| 226 |
+
space_id_startup = os.getenv("SPACE_ID")
|
| 227 |
|
| 228 |
if space_host_startup:
|
| 229 |
print(f"✅ SPACE_HOST found: {space_host_startup}")
|
|
|
|
| 231 |
else:
|
| 232 |
print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
|
| 233 |
|
| 234 |
+
if space_id_startup:
|
| 235 |
print(f"✅ SPACE_ID found: {space_id_startup}")
|
| 236 |
print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
|
| 237 |
print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
|
|
|
|
| 240 |
|
| 241 |
print("-"*(60 + len(" App Starting ")) + "\n")
|
| 242 |
|
| 243 |
+
print("Launching Gradio Interface for Real Agent Evaluation...")
|
| 244 |
demo.launch(debug=True, share=False)
|