Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,154 +1,155 @@
|
|
| 1 |
-
import os
|
| 2 |
-
import gradio as gr
|
| 3 |
-
import requests
|
| 4 |
-
import pandas as pd
|
| 5 |
-
from langchain import hub
|
| 6 |
-
from langchain.agents import AgentExecutor, create_react_agent
|
| 7 |
-
from langchain_community.tools import DuckDuckGoSearchRun
|
| 8 |
-
from langchain_huggingface import HuggingFaceEndpoint
|
| 9 |
-
|
| 10 |
-
# --- Constants ---
|
| 11 |
-
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 12 |
-
|
| 13 |
-
# --- New LangChain Agent Definition ---
|
| 14 |
-
class LangChainAgent:
|
| 15 |
-
def __init__(self):
|
| 16 |
-
print("Initializing LangChainAgent...")
|
| 17 |
-
|
| 18 |
-
# 1. Set up the LLM (The "Brain") using
|
| 19 |
-
self.llm = HuggingFaceEndpoint(
|
| 20 |
-
repo_id="
|
| 21 |
-
task="
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
response.
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
response.
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
f"
|
| 122 |
-
f"
|
| 123 |
-
f"
|
| 124 |
-
f"
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
gr.Markdown(
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
|
|
|
| 154 |
demo.launch()
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import gradio as gr
|
| 3 |
+
import requests
|
| 4 |
+
import pandas as pd
|
| 5 |
+
from langchain import hub
|
| 6 |
+
from langchain.agents import AgentExecutor, create_react_agent
|
| 7 |
+
from langchain_community.tools import DuckDuckGoSearchRun
|
| 8 |
+
from langchain_huggingface import HuggingFaceEndpoint
|
| 9 |
+
|
| 10 |
+
# --- Constants ---
|
| 11 |
+
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 12 |
+
|
| 13 |
+
# --- New LangChain Agent Definition ---
|
| 14 |
+
class LangChainAgent:
|
| 15 |
+
def __init__(self):
|
| 16 |
+
print("Initializing LangChainAgent...")
|
| 17 |
+
|
| 18 |
+
# 1. Set up the LLM (The "Brain") using a stable model
|
| 19 |
+
self.llm = HuggingFaceEndpoint(
|
| 20 |
+
repo_id="google/flan-t5-xxl",
|
| 21 |
+
task="text-generation",
|
| 22 |
+
model_kwargs={
|
| 23 |
+
"max_new_tokens": 512,
|
| 24 |
+
}
|
| 25 |
+
)
|
| 26 |
+
print("LLM initialized with google/flan-t5-xxl.")
|
| 27 |
+
|
| 28 |
+
# 2. Define the Tools
|
| 29 |
+
self.tools = [DuckDuckGoSearchRun()]
|
| 30 |
+
print("Tools initialized.")
|
| 31 |
+
|
| 32 |
+
# 3. Get the Prompt Template
|
| 33 |
+
self.prompt = hub.pull("hwchase17/react")
|
| 34 |
+
print("Prompt template pulled.")
|
| 35 |
+
|
| 36 |
+
# 4. Create the Agent
|
| 37 |
+
self.agent = create_react_agent(self.llm, self.tools, self.prompt)
|
| 38 |
+
print("Agent created.")
|
| 39 |
+
|
| 40 |
+
# 5. Create the Agent Executor
|
| 41 |
+
self.agent_executor = AgentExecutor(
|
| 42 |
+
agent=self.agent,
|
| 43 |
+
tools=self.tools,
|
| 44 |
+
verbose=True,
|
| 45 |
+
handle_parsing_errors=True,
|
| 46 |
+
max_iterations=5,
|
| 47 |
+
)
|
| 48 |
+
print("Agent Executor created. Initialization complete.")
|
| 49 |
+
|
| 50 |
+
def __call__(self, question: str) -> str:
|
| 51 |
+
"""
|
| 52 |
+
This method is executed for each question.
|
| 53 |
+
"""
|
| 54 |
+
print(f"Agent received question: {question}")
|
| 55 |
+
|
| 56 |
+
try:
|
| 57 |
+
response = self.agent_executor.invoke({"input": question})
|
| 58 |
+
final_answer = response.get("output", "Error: Could not parse final answer.")
|
| 59 |
+
except Exception as e:
|
| 60 |
+
print(f"Error during agent execution: {e}")
|
| 61 |
+
final_answer = "Error: Agent failed to execute."
|
| 62 |
+
|
| 63 |
+
print(f"Agent returning answer: {final_answer}")
|
| 64 |
+
return str(final_answer)
|
| 65 |
+
|
| 66 |
+
# --- Main Application Logic (Uses our new agent) ---
|
| 67 |
+
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
| 68 |
+
"""
|
| 69 |
+
Fetches all questions, runs the LangChainAgent on them, submits all answers,
|
| 70 |
+
and displays the results.
|
| 71 |
+
"""
|
| 72 |
+
space_id = os.getenv("SPACE_ID")
|
| 73 |
+
|
| 74 |
+
if profile:
|
| 75 |
+
username = f"{profile.username}"
|
| 76 |
+
print(f"User logged in: {username}")
|
| 77 |
+
else:
|
| 78 |
+
print("User not logged in.")
|
| 79 |
+
return "Please Login to Hugging Face with the button.", None
|
| 80 |
+
|
| 81 |
+
api_url = DEFAULT_API_URL
|
| 82 |
+
questions_url = f"{api_url}/questions"
|
| 83 |
+
submit_url = f"{api_url}/submit"
|
| 84 |
+
|
| 85 |
+
# 1. Instantiate Agent
|
| 86 |
+
try:
|
| 87 |
+
agent = LangChainAgent()
|
| 88 |
+
except Exception as e:
|
| 89 |
+
print(f"Error instantiating agent: {e}")
|
| 90 |
+
return f"Error initializing agent: {e}", None
|
| 91 |
+
|
| 92 |
+
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
| 93 |
+
|
| 94 |
+
# 2. Fetch Questions
|
| 95 |
+
try:
|
| 96 |
+
response = requests.get(questions_url, timeout=20)
|
| 97 |
+
response.raise_for_status()
|
| 98 |
+
questions_data = response.json()
|
| 99 |
+
except Exception as e:
|
| 100 |
+
return f"An unexpected error occurred fetching questions: {e}", None
|
| 101 |
+
|
| 102 |
+
# 3. Run your Agent
|
| 103 |
+
results_log = []
|
| 104 |
+
answers_payload = []
|
| 105 |
+
for item in questions_data:
|
| 106 |
+
task_id = item.get("task_id")
|
| 107 |
+
question_text = item.get("question")
|
| 108 |
+
submitted_answer = agent(question_text)
|
| 109 |
+
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
| 110 |
+
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
|
| 111 |
+
|
| 112 |
+
# 4. Prepare Submission
|
| 113 |
+
submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
|
| 114 |
+
|
| 115 |
+
# 5. Submit
|
| 116 |
+
try:
|
| 117 |
+
response = requests.post(submit_url, json=submission_data, timeout=60)
|
| 118 |
+
response.raise_for_status()
|
| 119 |
+
result_data = response.json()
|
| 120 |
+
final_status = (
|
| 121 |
+
f"Submission Successful!\n"
|
| 122 |
+
f"User: {result_data.get('username')}\n"
|
| 123 |
+
f"Overall Score: {result_data.get('score', 'N/A')}% "
|
| 124 |
+
f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
|
| 125 |
+
f"Message: {result_data.get('message', 'No message received.')}"
|
| 126 |
+
)
|
| 127 |
+
results_df = pd.DataFrame(results_log)
|
| 128 |
+
return final_status, results_df
|
| 129 |
+
except Exception as e:
|
| 130 |
+
status_message = f"An unexpected error occurred during submission: {e}"
|
| 131 |
+
results_df = pd.DataFrame(results_log)
|
| 132 |
+
return status_message, results_df
|
| 133 |
+
|
| 134 |
+
# --- Gradio Interface (Unchanged) ---
|
| 135 |
+
with gr.Blocks() as demo:
|
| 136 |
+
gr.Markdown("# Agent Evaluation Runner (LangChain Version)")
|
| 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 |
+
)
|
| 144 |
+
gr.LoginButton()
|
| 145 |
+
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
| 146 |
+
status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
|
| 147 |
+
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
| 148 |
+
|
| 149 |
+
run_button.click(
|
| 150 |
+
fn=run_and_submit_all,
|
| 151 |
+
outputs=[status_output, results_table]
|
| 152 |
+
)
|
| 153 |
+
|
| 154 |
+
if __name__ == "__main__":
|
| 155 |
demo.launch()
|