Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,27 +1,25 @@
|
|
|
|
|
|
|
|
| 1 |
import os
|
| 2 |
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 |
-
# --- Basic Agent Definition ---
|
| 12 |
-
# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
|
| 13 |
-
class BasicAgent:
|
| 14 |
-
def __init__(self):
|
| 15 |
-
print("BasicAgent initialized.")
|
| 16 |
-
def __call__(self, question: str) -> str:
|
| 17 |
-
print(f"Agent received question (first 50 chars): {question[:50]}...")
|
| 18 |
-
fixed_answer = "This is a default answer."
|
| 19 |
-
print(f"Agent returning fixed answer: {fixed_answer}")
|
| 20 |
-
return fixed_answer
|
| 21 |
|
| 22 |
def run_and_submit_all( profile: gr.OAuthProfile | None):
|
| 23 |
"""
|
| 24 |
-
Fetches all questions, runs the
|
| 25 |
and displays the results.
|
| 26 |
"""
|
| 27 |
# --- Determine HF Space Runtime URL and Repo URL ---
|
|
@@ -40,15 +38,18 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
| 40 |
|
| 41 |
# 1. Instantiate Agent ( modify this part to create your agent)
|
| 42 |
try:
|
| 43 |
-
|
|
|
|
|
|
|
| 44 |
except Exception as e:
|
| 45 |
-
print(f"Error instantiating agent: {e}")
|
| 46 |
-
return f"Error initializing agent: {e}", None
|
| 47 |
# 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)
|
| 48 |
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
| 49 |
print(agent_code)
|
| 50 |
|
| 51 |
# 2. Fetch Questions
|
|
|
|
| 52 |
print(f"Fetching questions from: {questions_url}")
|
| 53 |
try:
|
| 54 |
response = requests.get(questions_url, timeout=15)
|
|
@@ -69,6 +70,7 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
| 69 |
print(f"An unexpected error occurred fetching questions: {e}")
|
| 70 |
return f"An unexpected error occurred fetching questions: {e}", None
|
| 71 |
|
|
|
|
| 72 |
# 3. Run your Agent
|
| 73 |
results_log = []
|
| 74 |
answers_payload = []
|
|
@@ -80,23 +82,42 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
| 80 |
print(f"Skipping item with missing task_id or question: {item}")
|
| 81 |
continue
|
| 82 |
try:
|
| 83 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 84 |
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
| 85 |
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
|
| 86 |
except Exception as e:
|
| 87 |
-
print(f"Error running agent on task {task_id}: {e}")
|
| 88 |
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
|
| 89 |
|
| 90 |
if not answers_payload:
|
| 91 |
print("Agent did not produce any answers to submit.")
|
|
|
|
| 92 |
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
| 93 |
|
| 94 |
-
|
|
|
|
| 95 |
submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
|
| 96 |
status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
|
| 97 |
print(status_update)
|
| 98 |
|
| 99 |
# 5. Submit
|
|
|
|
| 100 |
print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
|
| 101 |
try:
|
| 102 |
response = requests.post(submit_url, json=submission_data, timeout=60)
|
|
@@ -142,14 +163,15 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
| 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.
|
| 152 |
-
3.
|
|
|
|
| 153 |
|
| 154 |
---
|
| 155 |
**Disclaimers:**
|
|
@@ -192,6 +214,6 @@ 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)
|
| 197 |
-
|
|
|
|
| 1 |
+
# --- START OF FILE app.py ---
|
| 2 |
+
|
| 3 |
import os
|
| 4 |
import gradio as gr
|
| 5 |
import requests
|
| 6 |
import inspect
|
| 7 |
import pandas as pd
|
| 8 |
+
from dotenv import load_dotenv # Added
|
| 9 |
+
from agent import build_graph # Added
|
| 10 |
+
from langchain_core.messages import HumanMessage # Added
|
| 11 |
+
|
| 12 |
+
load_dotenv() # Added
|
| 13 |
|
| 14 |
# (Keep Constants as is)
|
| 15 |
# --- Constants ---
|
| 16 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 17 |
|
| 18 |
+
# --- Basic Agent Definition --- REMOVED THIS PART
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
|
| 20 |
def run_and_submit_all( profile: gr.OAuthProfile | None):
|
| 21 |
"""
|
| 22 |
+
Fetches all questions, runs the LangGraph Agent on them, submits all answers,
|
| 23 |
and displays the results.
|
| 24 |
"""
|
| 25 |
# --- Determine HF Space Runtime URL and Repo URL ---
|
|
|
|
| 38 |
|
| 39 |
# 1. Instantiate Agent ( modify this part to create your agent)
|
| 40 |
try:
|
| 41 |
+
# Use the build_graph function from agent.py
|
| 42 |
+
agent_graph = build_graph() # Changed from BasicAgent()
|
| 43 |
+
print("LangGraph agent initialized.")
|
| 44 |
except Exception as e:
|
| 45 |
+
print(f"Error instantiating agent graph: {e}")
|
| 46 |
+
return f"Error initializing agent graph: {e}", None
|
| 47 |
# 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)
|
| 48 |
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
| 49 |
print(agent_code)
|
| 50 |
|
| 51 |
# 2. Fetch Questions
|
| 52 |
+
# ... (rest of fetching code is the same) ...
|
| 53 |
print(f"Fetching questions from: {questions_url}")
|
| 54 |
try:
|
| 55 |
response = requests.get(questions_url, timeout=15)
|
|
|
|
| 70 |
print(f"An unexpected error occurred fetching questions: {e}")
|
| 71 |
return f"An unexpected error occurred fetching questions: {e}", None
|
| 72 |
|
| 73 |
+
|
| 74 |
# 3. Run your Agent
|
| 75 |
results_log = []
|
| 76 |
answers_payload = []
|
|
|
|
| 82 |
print(f"Skipping item with missing task_id or question: {item}")
|
| 83 |
continue
|
| 84 |
try:
|
| 85 |
+
# Invoke the LangGraph agent
|
| 86 |
+
result_state = agent_graph.invoke({"messages": [HumanMessage(content=question_text)]})
|
| 87 |
+
|
| 88 |
+
# Extract the final answer from the last message
|
| 89 |
+
submitted_answer = "Error: Agent did not provide a response." # Default in case extraction fails
|
| 90 |
+
if result_state and "messages" in result_state and result_state["messages"]:
|
| 91 |
+
last_message = result_state["messages"][-1]
|
| 92 |
+
# The final content is typically in the content attribute of the last message
|
| 93 |
+
if hasattr(last_message, 'content') and last_message.content:
|
| 94 |
+
submitted_answer = last_message.content
|
| 95 |
+
# else: Handle cases where the last message might be a tool message etc.,
|
| 96 |
+
# for simplicity, we just use the default error message if content is missing.
|
| 97 |
+
|
| 98 |
+
# Ensure submitted_answer is a string
|
| 99 |
+
if not isinstance(submitted_answer, str):
|
| 100 |
+
submitted_answer = str(submitted_answer)
|
| 101 |
+
|
| 102 |
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
| 103 |
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
|
| 104 |
except Exception as e:
|
| 105 |
+
print(f"Error running agent graph on task {task_id}: {e}")
|
| 106 |
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
|
| 107 |
|
| 108 |
if not answers_payload:
|
| 109 |
print("Agent did not produce any answers to submit.")
|
| 110 |
+
# Even if no answers, show the log of errors
|
| 111 |
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
| 112 |
|
| 113 |
+
|
| 114 |
+
# 4. Prepare Submission
|
| 115 |
submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
|
| 116 |
status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
|
| 117 |
print(status_update)
|
| 118 |
|
| 119 |
# 5. Submit
|
| 120 |
+
# ... (rest of submission code is the same) ...
|
| 121 |
print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
|
| 122 |
try:
|
| 123 |
response = requests.post(submit_url, json=submission_data, timeout=60)
|
|
|
|
| 163 |
|
| 164 |
# --- Build Gradio Interface using Blocks ---
|
| 165 |
with gr.Blocks() as demo:
|
| 166 |
+
gr.Markdown("# LangGraph Agent Evaluation Runner") # Updated title
|
| 167 |
gr.Markdown(
|
| 168 |
"""
|
| 169 |
**Instructions:**
|
| 170 |
|
| 171 |
+
1. Please clone this space, then modify the code in `agent.py` and `app.py` to define your agent's logic, the tools, the necessary packages, etc ...
|
| 172 |
+
2. **Make sure you have your `DEEPSEEK_API_KEY` set as a Space Secret.**
|
| 173 |
+
3. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
|
| 174 |
+
4. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
|
| 175 |
|
| 176 |
---
|
| 177 |
**Disclaimers:**
|
|
|
|
| 214 |
|
| 215 |
print("-"*(60 + len(" App Starting ")) + "\n")
|
| 216 |
|
| 217 |
+
print("Launching Gradio Interface for LangGraph Agent Evaluation...") # Updated message
|
| 218 |
+
# demo.launch(debug=True, share=False)
|
| 219 |
+
demo.launch(debug=True, share=False, auth=None) # Keep auth=None for public space or remove for gated
|