Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,41 +1,42 @@
|
|
| 1 |
""" Basic Agent Evaluation Runner"""
|
| 2 |
import os
|
|
|
|
| 3 |
import gradio as gr
|
| 4 |
import requests
|
| 5 |
import pandas as pd
|
| 6 |
from langchain_core.messages import HumanMessage
|
| 7 |
-
from
|
| 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 |
-
|
| 18 |
-
|
| 19 |
class BasicAgent:
|
| 20 |
"""A langgraph agent."""
|
| 21 |
def __init__(self):
|
| 22 |
print("BasicAgent initialized.")
|
| 23 |
-
|
|
|
|
| 24 |
def __call__(self, question: str) -> str:
|
| 25 |
print(f"Agent received question: {question}")
|
|
|
|
|
|
|
|
|
|
| 26 |
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
|
|
|
|
|
|
| 37 |
|
| 38 |
-
def run_and_submit_all(
|
| 39 |
"""
|
| 40 |
Fetches all questions, runs the BasicAgent on them, submits all answers,
|
| 41 |
and displays the results.
|
|
@@ -54,13 +55,13 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
| 54 |
questions_url = f"{api_url}/questions"
|
| 55 |
submit_url = f"{api_url}/submit"
|
| 56 |
|
| 57 |
-
# 1. Instantiate Agent
|
| 58 |
try:
|
| 59 |
agent = BasicAgent()
|
| 60 |
except Exception as e:
|
| 61 |
print(f"Error instantiating agent: {e}")
|
| 62 |
return f"Error initializing agent: {e}", None
|
| 63 |
-
|
| 64 |
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
| 65 |
print(agent_code)
|
| 66 |
|
|
@@ -77,10 +78,6 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
| 77 |
except requests.exceptions.RequestException as e:
|
| 78 |
print(f"Error fetching questions: {e}")
|
| 79 |
return f"Error fetching questions: {e}", None
|
| 80 |
-
except requests.exceptions.JSONDecodeError as e:
|
| 81 |
-
print(f"Error decoding JSON response from questions endpoint: {e}")
|
| 82 |
-
print(f"Response text: {response.text[:500]}")
|
| 83 |
-
return f"Error decoding server response for questions: {e}", None
|
| 84 |
except Exception as e:
|
| 85 |
print(f"An unexpected error occurred fetching questions: {e}")
|
| 86 |
return f"An unexpected error occurred fetching questions: {e}", None
|
|
@@ -128,47 +125,27 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
| 128 |
print("Submission successful.")
|
| 129 |
results_df = pd.DataFrame(results_log)
|
| 130 |
return final_status, results_df
|
| 131 |
-
except requests.exceptions.HTTPError as e:
|
| 132 |
-
error_detail = f"Server responded with status {e.response.status_code}."
|
| 133 |
-
try:
|
| 134 |
-
error_json = e.response.json()
|
| 135 |
-
error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
|
| 136 |
-
except requests.exceptions.JSONDecodeError:
|
| 137 |
-
error_detail += f" Response: {e.response.text[:500]}"
|
| 138 |
-
status_message = f"Submission Failed: {error_detail}"
|
| 139 |
-
print(status_message)
|
| 140 |
-
results_df = pd.DataFrame(results_log)
|
| 141 |
-
return status_message, results_df
|
| 142 |
-
except requests.exceptions.Timeout:
|
| 143 |
-
status_message = "Submission Failed: The request timed out."
|
| 144 |
-
print(status_message)
|
| 145 |
-
results_df = pd.DataFrame(results_log)
|
| 146 |
-
return status_message, results_df
|
| 147 |
-
except requests.exceptions.RequestException as e:
|
| 148 |
-
status_message = f"Submission Failed: Network error - {e}"
|
| 149 |
-
print(status_message)
|
| 150 |
-
results_df = pd.DataFrame(results_log)
|
| 151 |
-
return status_message, results_df
|
| 152 |
except Exception as e:
|
| 153 |
-
status_message = f"
|
| 154 |
print(status_message)
|
| 155 |
results_df = pd.DataFrame(results_log)
|
| 156 |
return status_message, results_df
|
| 157 |
|
| 158 |
-
|
| 159 |
# --- Build Gradio Interface using Blocks ---
|
| 160 |
with gr.Blocks() as demo:
|
| 161 |
-
gr.Markdown("#
|
| 162 |
gr.Markdown(
|
| 163 |
"""
|
| 164 |
**Instructions:**
|
| 165 |
-
1.
|
| 166 |
-
2.
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
|
|
|
|
|
|
| 172 |
"""
|
| 173 |
)
|
| 174 |
|
|
@@ -177,7 +154,6 @@ with gr.Blocks() as demo:
|
|
| 177 |
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
| 178 |
|
| 179 |
status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
|
| 180 |
-
# Removed max_rows=10 from DataFrame constructor
|
| 181 |
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
| 182 |
|
| 183 |
run_button.click(
|
|
@@ -187,24 +163,4 @@ with gr.Blocks() as demo:
|
|
| 187 |
|
| 188 |
if __name__ == "__main__":
|
| 189 |
print("\n" + "-"*30 + " App Starting " + "-"*30)
|
| 190 |
-
|
| 191 |
-
space_host_startup = os.getenv("SPACE_HOST")
|
| 192 |
-
space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
|
| 193 |
-
|
| 194 |
-
if space_host_startup:
|
| 195 |
-
print(f"✅ SPACE_HOST found: {space_host_startup}")
|
| 196 |
-
print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
|
| 197 |
-
else:
|
| 198 |
-
print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
|
| 199 |
-
|
| 200 |
-
if space_id_startup: # Print repo URLs if SPACE_ID is found
|
| 201 |
-
print(f"✅ SPACE_ID found: {space_id_startup}")
|
| 202 |
-
print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
|
| 203 |
-
print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
|
| 204 |
-
else:
|
| 205 |
-
print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
|
| 206 |
-
|
| 207 |
-
print("-"*(60 + len(" App Starting ")) + "\n")
|
| 208 |
-
|
| 209 |
-
print("Launching Gradio Interface for Basic Agent Evaluation...")
|
| 210 |
-
demo.launch(debug=True, share=False)
|
|
|
|
| 1 |
""" Basic Agent Evaluation Runner"""
|
| 2 |
import os
|
| 3 |
+
import inspect
|
| 4 |
import gradio as gr
|
| 5 |
import requests
|
| 6 |
import pandas as pd
|
| 7 |
from langchain_core.messages import HumanMessage
|
| 8 |
+
from agent import build_graph
|
| 9 |
|
|
|
|
|
|
|
|
|
|
| 10 |
# --- Constants ---
|
| 11 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 12 |
|
| 13 |
# --- Basic Agent Definition ---
|
|
|
|
|
|
|
|
|
|
| 14 |
class BasicAgent:
|
| 15 |
"""A langgraph agent."""
|
| 16 |
def __init__(self):
|
| 17 |
print("BasicAgent initialized.")
|
| 18 |
+
self.graph = build_graph(provider="groq") # Using Groq as default
|
| 19 |
+
|
| 20 |
def __call__(self, question: str) -> str:
|
| 21 |
print(f"Agent received question: {question}")
|
| 22 |
+
# Wrap the question in a HumanMessage from langchain_core
|
| 23 |
+
messages = [HumanMessage(content=question)]
|
| 24 |
+
config = {"configurable": {"thread_id": f"eval_{hash(question)}"}}
|
| 25 |
|
| 26 |
+
try:
|
| 27 |
+
result = self.graph.invoke({"messages": messages}, config)
|
| 28 |
+
answer = result['messages'][-1].content
|
| 29 |
+
|
| 30 |
+
# Extract final answer if present
|
| 31 |
+
if "FINAL ANSWER:" in answer:
|
| 32 |
+
return answer.split("FINAL ANSWER:")[-1].strip()
|
| 33 |
+
else:
|
| 34 |
+
return answer.strip()
|
| 35 |
+
|
| 36 |
+
except Exception as e:
|
| 37 |
+
return f"Error: {str(e)}"
|
| 38 |
|
| 39 |
+
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
| 40 |
"""
|
| 41 |
Fetches all questions, runs the BasicAgent on them, submits all answers,
|
| 42 |
and displays the results.
|
|
|
|
| 55 |
questions_url = f"{api_url}/questions"
|
| 56 |
submit_url = f"{api_url}/submit"
|
| 57 |
|
| 58 |
+
# 1. Instantiate Agent
|
| 59 |
try:
|
| 60 |
agent = BasicAgent()
|
| 61 |
except Exception as e:
|
| 62 |
print(f"Error instantiating agent: {e}")
|
| 63 |
return f"Error initializing agent: {e}", None
|
| 64 |
+
|
| 65 |
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
| 66 |
print(agent_code)
|
| 67 |
|
|
|
|
| 78 |
except requests.exceptions.RequestException as e:
|
| 79 |
print(f"Error fetching questions: {e}")
|
| 80 |
return f"Error fetching questions: {e}", None
|
|
|
|
|
|
|
|
|
|
|
|
|
| 81 |
except Exception as e:
|
| 82 |
print(f"An unexpected error occurred fetching questions: {e}")
|
| 83 |
return f"An unexpected error occurred fetching questions: {e}", None
|
|
|
|
| 125 |
print("Submission successful.")
|
| 126 |
results_df = pd.DataFrame(results_log)
|
| 127 |
return final_status, results_df
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 128 |
except Exception as e:
|
| 129 |
+
status_message = f"Submission Failed: {e}"
|
| 130 |
print(status_message)
|
| 131 |
results_df = pd.DataFrame(results_log)
|
| 132 |
return status_message, results_df
|
| 133 |
|
|
|
|
| 134 |
# --- Build Gradio Interface using Blocks ---
|
| 135 |
with gr.Blocks() as demo:
|
| 136 |
+
gr.Markdown("# LangGraph Agent Evaluation Runner")
|
| 137 |
gr.Markdown(
|
| 138 |
"""
|
| 139 |
**Instructions:**
|
| 140 |
+
1. Log in to your Hugging Face account using the button below.
|
| 141 |
+
2. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
|
| 142 |
+
|
| 143 |
+
**Agent Features:**
|
| 144 |
+
- Uses FAISS vector database for similar question retrieval
|
| 145 |
+
- Includes mathematical calculation tools
|
| 146 |
+
- Web search capabilities (Tavily, Wikipedia, ArXiv)
|
| 147 |
+
- Rate limiting for free tier models
|
| 148 |
+
- Best free models: Groq Llama 3.3 70B, Gemini 2.0 Flash, NVIDIA Llama 3.1 70B
|
| 149 |
"""
|
| 150 |
)
|
| 151 |
|
|
|
|
| 154 |
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
| 155 |
|
| 156 |
status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
|
|
|
|
| 157 |
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
| 158 |
|
| 159 |
run_button.click(
|
|
|
|
| 163 |
|
| 164 |
if __name__ == "__main__":
|
| 165 |
print("\n" + "-"*30 + " App Starting " + "-"*30)
|
| 166 |
+
demo.launch(debug=True, share=False)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|