Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,123 +1,47 @@
|
|
|
|
|
| 1 |
import os
|
|
|
|
| 2 |
import gradio as gr
|
| 3 |
import requests
|
| 4 |
-
import inspect
|
| 5 |
import pandas as pd
|
|
|
|
| 6 |
from agent import build_graph
|
| 7 |
-
from dotenv import load_dotenv
|
| 8 |
-
from langgraph.graph import START, StateGraph, MessagesState
|
| 9 |
-
from langgraph.prebuilt import tools_condition
|
| 10 |
-
from langgraph.prebuilt import ToolNode
|
| 11 |
-
from langchain_google_genai import ChatGoogleGenerativeAI
|
| 12 |
-
from langchain_groq import ChatGroq
|
| 13 |
-
from langchain_huggingface import (
|
| 14 |
-
ChatHuggingFace,
|
| 15 |
-
HuggingFaceEndpoint,
|
| 16 |
-
HuggingFaceEmbeddings,
|
| 17 |
-
)
|
| 18 |
-
from langchain_community.tools.tavily_search import TavilySearchResults
|
| 19 |
-
from langchain_community.document_loaders import WikipediaLoader
|
| 20 |
-
from langchain_community.document_loaders import ArxivLoader
|
| 21 |
-
from langchain_community.vectorstores import SupabaseVectorStore
|
| 22 |
-
from langchain_core.messages import SystemMessage, HumanMessage
|
| 23 |
-
from langchain_core.tools import tool
|
| 24 |
-
from langchain.tools.retriever import create_retriever_tool
|
| 25 |
-
from supabase.client import Client, create_client
|
| 26 |
|
| 27 |
-
|
| 28 |
-
from langgraph.graph import START, StateGraph, MessagesState
|
| 29 |
-
from langgraph.prebuilt import tools_condition
|
| 30 |
-
from langgraph.prebuilt import ToolNode
|
| 31 |
-
from langchain_google_genai import ChatGoogleGenerativeAI
|
| 32 |
-
from langchain_groq import ChatGroq
|
| 33 |
-
from langchain_huggingface import ChatHuggingFace, HuggingFaceEndpoint, HuggingFaceEmbeddings
|
| 34 |
-
from langchain_community.tools.tavily_search import TavilySearchResults
|
| 35 |
-
from langchain_community.document_loaders import WikipediaLoader
|
| 36 |
-
from langchain_community.document_loaders import ArxivLoader
|
| 37 |
-
from langchain_community.vectorstores import SupabaseVectorStore
|
| 38 |
-
from langchain_core.messages import SystemMessage, HumanMessage
|
| 39 |
-
from langchain_core.tools import tool
|
| 40 |
-
from langchain.tools.retriever import create_retriever_tool
|
| 41 |
-
from supabase.client import Client, create_client
|
| 42 |
|
| 43 |
# (Keep Constants as is)
|
| 44 |
# --- Constants ---
|
| 45 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 46 |
|
| 47 |
-
|
| 48 |
# --- Basic Agent Definition ---
|
| 49 |
# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
|
| 50 |
-
class BasicAgent:
|
| 51 |
-
"""A langgraph agent with improved error handling."""
|
| 52 |
|
|
|
|
|
|
|
|
|
|
| 53 |
def __init__(self):
|
| 54 |
print("BasicAgent initialized.")
|
| 55 |
-
|
| 56 |
-
self.graph = build_graph()
|
| 57 |
-
print("Graph built successfully.")
|
| 58 |
-
except Exception as e:
|
| 59 |
-
print(f"Error building graph: {e}")
|
| 60 |
-
# Create a fallback simple graph if main graph fails
|
| 61 |
-
self.graph = self._create_fallback_graph()
|
| 62 |
-
|
| 63 |
-
def _create_fallback_graph(self):
|
| 64 |
-
"""Create a simple fallback graph when main graph fails."""
|
| 65 |
-
print("Creating fallback graph...")
|
| 66 |
-
try:
|
| 67 |
-
from langchain_groq import ChatGroq
|
| 68 |
-
llm = ChatGroq(model="qwen-qwq-32b", temperature=0)
|
| 69 |
-
|
| 70 |
-
def simple_assistant(state: MessagesState):
|
| 71 |
-
"""Simple assistant without tools"""
|
| 72 |
-
return {"messages": [llm.invoke(state["messages"])]}
|
| 73 |
-
|
| 74 |
-
builder = StateGraph(MessagesState)
|
| 75 |
-
builder.add_node("assistant", simple_assistant)
|
| 76 |
-
builder.add_edge(START, "assistant")
|
| 77 |
-
|
| 78 |
-
return builder.compile()
|
| 79 |
-
except Exception as e:
|
| 80 |
-
print(f"Failed to create fallback graph: {e}")
|
| 81 |
-
return None
|
| 82 |
|
| 83 |
def __call__(self, question: str) -> str:
|
| 84 |
print(f"Agent received question (first 50 chars): {question[:50]}...")
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
messages = [HumanMessage(content=question)]
|
| 91 |
-
result = self.graph.invoke({"messages": messages})
|
| 92 |
-
|
| 93 |
-
# Safely extract the answer
|
| 94 |
-
if result and "messages" in result and len(result["messages"]) > 0:
|
| 95 |
-
last_message = result["messages"][-1]
|
| 96 |
-
if hasattr(last_message, 'content'):
|
| 97 |
-
answer = last_message.content
|
| 98 |
-
print(f"Agent response (first 50 chars): {str(answer)[:50]}...")
|
| 99 |
-
return str(answer)
|
| 100 |
-
else:
|
| 101 |
-
return "Error: Received invalid message format from agent."
|
| 102 |
-
else:
|
| 103 |
-
return "Error: Agent did not produce a valid response."
|
| 104 |
-
|
| 105 |
-
except Exception as e:
|
| 106 |
-
error_msg = f"Error during agent execution: {str(e)}"
|
| 107 |
-
print(error_msg)
|
| 108 |
-
return error_msg
|
| 109 |
|
| 110 |
|
| 111 |
-
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
| 112 |
"""
|
| 113 |
Fetches all questions, runs the BasicAgent on them, submits all answers,
|
| 114 |
-
and displays the results
|
| 115 |
"""
|
| 116 |
# --- Determine HF Space Runtime URL and Repo URL ---
|
| 117 |
-
space_id = os.getenv("SPACE_ID")
|
| 118 |
|
| 119 |
if profile:
|
| 120 |
-
username
|
| 121 |
print(f"User logged in: {username}")
|
| 122 |
else:
|
| 123 |
print("User not logged in.")
|
|
@@ -130,14 +54,11 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
| 130 |
# 1. Instantiate Agent ( modify this part to create your agent)
|
| 131 |
try:
|
| 132 |
agent = BasicAgent()
|
| 133 |
-
if agent.graph is None:
|
| 134 |
-
return "Error: Failed to initialize agent properly.", None
|
| 135 |
except Exception as e:
|
| 136 |
print(f"Error instantiating agent: {e}")
|
| 137 |
return f"Error initializing agent: {e}", None
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main" if space_id else "Local Development"
|
| 141 |
print(agent_code)
|
| 142 |
|
| 143 |
# 2. Fetch Questions
|
|
@@ -147,16 +68,16 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
| 147 |
response.raise_for_status()
|
| 148 |
questions_data = response.json()
|
| 149 |
if not questions_data:
|
| 150 |
-
|
| 151 |
-
|
| 152 |
print(f"Fetched {len(questions_data)} questions.")
|
| 153 |
except requests.exceptions.RequestException as e:
|
| 154 |
print(f"Error fetching questions: {e}")
|
| 155 |
return f"Error fetching questions: {e}", None
|
| 156 |
except requests.exceptions.JSONDecodeError as e:
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
except Exception as e:
|
| 161 |
print(f"An unexpected error occurred fetching questions: {e}")
|
| 162 |
return f"An unexpected error occurred fetching questions: {e}", None
|
|
@@ -165,62 +86,26 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
| 165 |
results_log = []
|
| 166 |
answers_payload = []
|
| 167 |
print(f"Running agent on {len(questions_data)} questions...")
|
| 168 |
-
|
| 169 |
-
for i, item in enumerate(questions_data):
|
| 170 |
task_id = item.get("task_id")
|
| 171 |
question_text = item.get("question")
|
| 172 |
-
|
| 173 |
-
print(f"Processing question {i+1}/{len(questions_data)}: {task_id}")
|
| 174 |
-
|
| 175 |
if not task_id or question_text is None:
|
| 176 |
print(f"Skipping item with missing task_id or question: {item}")
|
| 177 |
continue
|
| 178 |
-
|
| 179 |
try:
|
| 180 |
submitted_answer = agent(question_text)
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
if not submitted_answer or submitted_answer.strip() == "":
|
| 184 |
-
submitted_answer = "Error: Agent produced empty response."
|
| 185 |
-
|
| 186 |
-
answers_payload.append(
|
| 187 |
-
{"task_id": task_id, "submitted_answer": submitted_answer}
|
| 188 |
-
)
|
| 189 |
-
results_log.append(
|
| 190 |
-
{
|
| 191 |
-
"Task ID": task_id,
|
| 192 |
-
"Question": question_text[:100] + "..." if len(question_text) > 100 else question_text,
|
| 193 |
-
"Submitted Answer": submitted_answer[:200] + "..." if len(str(submitted_answer)) > 200 else str(submitted_answer),
|
| 194 |
-
}
|
| 195 |
-
)
|
| 196 |
-
print(f"Successfully processed question {i+1}")
|
| 197 |
-
|
| 198 |
except Exception as e:
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
# Still add to payload with error message
|
| 203 |
-
answers_payload.append(
|
| 204 |
-
{"task_id": task_id, "submitted_answer": error_msg}
|
| 205 |
-
)
|
| 206 |
-
results_log.append(
|
| 207 |
-
{
|
| 208 |
-
"Task ID": task_id,
|
| 209 |
-
"Question": question_text[:100] + "..." if len(question_text) > 100 else question_text,
|
| 210 |
-
"Submitted Answer": error_msg,
|
| 211 |
-
}
|
| 212 |
-
)
|
| 213 |
|
| 214 |
if not answers_payload:
|
| 215 |
print("Agent did not produce any answers to submit.")
|
| 216 |
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
| 217 |
|
| 218 |
-
# 4. Prepare Submission
|
| 219 |
-
submission_data = {
|
| 220 |
-
"username": username.strip(),
|
| 221 |
-
"agent_code": agent_code,
|
| 222 |
-
"answers": answers_payload,
|
| 223 |
-
}
|
| 224 |
status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
|
| 225 |
print(status_update)
|
| 226 |
|
|
@@ -288,19 +173,20 @@ with gr.Blocks() as demo:
|
|
| 288 |
|
| 289 |
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
| 290 |
|
| 291 |
-
status_output = gr.Textbox(
|
| 292 |
-
label="Run Status / Submission Result", lines=5, interactive=False
|
| 293 |
-
)
|
| 294 |
# Removed max_rows=10 from DataFrame constructor
|
| 295 |
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
| 296 |
|
| 297 |
-
run_button.click(
|
|
|
|
|
|
|
|
|
|
| 298 |
|
| 299 |
if __name__ == "__main__":
|
| 300 |
-
print("\n" + "-"
|
| 301 |
# Check for SPACE_HOST and SPACE_ID at startup for information
|
| 302 |
space_host_startup = os.getenv("SPACE_HOST")
|
| 303 |
-
space_id_startup = os.getenv("SPACE_ID")
|
| 304 |
|
| 305 |
if space_host_startup:
|
| 306 |
print(f"✅ SPACE_HOST found: {space_host_startup}")
|
|
@@ -308,18 +194,14 @@ if __name__ == "__main__":
|
|
| 308 |
else:
|
| 309 |
print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
|
| 310 |
|
| 311 |
-
if space_id_startup:
|
| 312 |
print(f"✅ SPACE_ID found: {space_id_startup}")
|
| 313 |
print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
|
| 314 |
-
print(
|
| 315 |
-
f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main"
|
| 316 |
-
)
|
| 317 |
else:
|
| 318 |
-
print(
|
| 319 |
-
"ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined."
|
| 320 |
-
)
|
| 321 |
|
| 322 |
-
print("-"
|
| 323 |
|
| 324 |
print("Launching Gradio Interface for Basic Agent Evaluation...")
|
| 325 |
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 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
|
| 12 |
# (Keep Constants as is)
|
| 13 |
# --- Constants ---
|
| 14 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 15 |
|
|
|
|
| 16 |
# --- Basic Agent Definition ---
|
| 17 |
# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
|
|
|
|
|
|
|
| 18 |
|
| 19 |
+
|
| 20 |
+
class BasicAgent:
|
| 21 |
+
"""A langgraph agent."""
|
| 22 |
def __init__(self):
|
| 23 |
print("BasicAgent initialized.")
|
| 24 |
+
self.graph = build_graph()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
|
| 26 |
def __call__(self, question: str) -> str:
|
| 27 |
print(f"Agent received question (first 50 chars): {question[:50]}...")
|
| 28 |
+
messages = [HumanMessage(content=question)]
|
| 29 |
+
result = self.graph.invoke({"messages": messages})
|
| 30 |
+
answer = result['messages'][-1].content
|
| 31 |
+
return answer # kein [14:] mehr nötig!
|
| 32 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
|
| 34 |
|
| 35 |
+
def run_and_submit_all( profile: gr.OAuthProfile | None):
|
| 36 |
"""
|
| 37 |
Fetches all questions, runs the BasicAgent on them, submits all answers,
|
| 38 |
+
and displays the results.
|
| 39 |
"""
|
| 40 |
# --- Determine HF Space Runtime URL and Repo URL ---
|
| 41 |
+
space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
|
| 42 |
|
| 43 |
if profile:
|
| 44 |
+
username= f"{profile.username}"
|
| 45 |
print(f"User logged in: {username}")
|
| 46 |
else:
|
| 47 |
print("User not logged in.")
|
|
|
|
| 54 |
# 1. Instantiate Agent ( modify this part to create your agent)
|
| 55 |
try:
|
| 56 |
agent = BasicAgent()
|
|
|
|
|
|
|
| 57 |
except Exception as e:
|
| 58 |
print(f"Error instantiating agent: {e}")
|
| 59 |
return f"Error initializing agent: {e}", None
|
| 60 |
+
# 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)
|
| 61 |
+
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
|
|
|
| 62 |
print(agent_code)
|
| 63 |
|
| 64 |
# 2. Fetch Questions
|
|
|
|
| 68 |
response.raise_for_status()
|
| 69 |
questions_data = response.json()
|
| 70 |
if not questions_data:
|
| 71 |
+
print("Fetched questions list is empty.")
|
| 72 |
+
return "Fetched questions list is empty or invalid format.", None
|
| 73 |
print(f"Fetched {len(questions_data)} questions.")
|
| 74 |
except requests.exceptions.RequestException as e:
|
| 75 |
print(f"Error fetching questions: {e}")
|
| 76 |
return f"Error fetching questions: {e}", None
|
| 77 |
except requests.exceptions.JSONDecodeError as e:
|
| 78 |
+
print(f"Error decoding JSON response from questions endpoint: {e}")
|
| 79 |
+
print(f"Response text: {response.text[:500]}")
|
| 80 |
+
return f"Error decoding server response for 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
|
|
|
|
| 86 |
results_log = []
|
| 87 |
answers_payload = []
|
| 88 |
print(f"Running agent on {len(questions_data)} questions...")
|
| 89 |
+
for item in questions_data:
|
|
|
|
| 90 |
task_id = item.get("task_id")
|
| 91 |
question_text = item.get("question")
|
|
|
|
|
|
|
|
|
|
| 92 |
if not task_id or question_text is None:
|
| 93 |
print(f"Skipping item with missing task_id or question: {item}")
|
| 94 |
continue
|
|
|
|
| 95 |
try:
|
| 96 |
submitted_answer = agent(question_text)
|
| 97 |
+
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
| 98 |
+
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 99 |
except Exception as e:
|
| 100 |
+
print(f"Error running agent on task {task_id}: {e}")
|
| 101 |
+
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 102 |
|
| 103 |
if not answers_payload:
|
| 104 |
print("Agent did not produce any answers to submit.")
|
| 105 |
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
| 106 |
|
| 107 |
+
# 4. Prepare Submission
|
| 108 |
+
submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
|
|
|
|
|
|
|
|
|
|
|
|
|
| 109 |
status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
|
| 110 |
print(status_update)
|
| 111 |
|
|
|
|
| 173 |
|
| 174 |
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
| 175 |
|
| 176 |
+
status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
|
|
|
|
|
|
|
| 177 |
# Removed max_rows=10 from DataFrame constructor
|
| 178 |
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
| 179 |
|
| 180 |
+
run_button.click(
|
| 181 |
+
fn=run_and_submit_all,
|
| 182 |
+
outputs=[status_output, results_table]
|
| 183 |
+
)
|
| 184 |
|
| 185 |
if __name__ == "__main__":
|
| 186 |
+
print("\n" + "-"*30 + " App Starting " + "-"*30)
|
| 187 |
# Check for SPACE_HOST and SPACE_ID at startup for information
|
| 188 |
space_host_startup = os.getenv("SPACE_HOST")
|
| 189 |
+
space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
|
| 190 |
|
| 191 |
if space_host_startup:
|
| 192 |
print(f"✅ SPACE_HOST found: {space_host_startup}")
|
|
|
|
| 194 |
else:
|
| 195 |
print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
|
| 196 |
|
| 197 |
+
if space_id_startup: # Print repo URLs if SPACE_ID is found
|
| 198 |
print(f"✅ SPACE_ID found: {space_id_startup}")
|
| 199 |
print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
|
| 200 |
+
print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
|
|
|
|
|
|
|
| 201 |
else:
|
| 202 |
+
print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
|
|
|
|
|
|
|
| 203 |
|
| 204 |
+
print("-"*(60 + len(" App Starting ")) + "\n")
|
| 205 |
|
| 206 |
print("Launching Gradio Interface for Basic Agent Evaluation...")
|
| 207 |
demo.launch(debug=True, share=False)
|