Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -3,20 +3,23 @@ import gradio as gr
|
|
| 3 |
import requests
|
| 4 |
import pandas as pd
|
| 5 |
from typing import TypedDict, Annotated, Sequence
|
| 6 |
-
|
| 7 |
-
from
|
|
|
|
|
|
|
| 8 |
from langchain_community.tools import DuckDuckGoSearchRun
|
| 9 |
from langchain_huggingface import HuggingFaceEndpoint
|
| 10 |
-
from langgraph.
|
|
|
|
| 11 |
|
| 12 |
# --- Main Application Logic ---
|
| 13 |
|
| 14 |
-
# This
|
|
|
|
| 15 |
class AgentState(TypedDict):
|
| 16 |
-
messages: Annotated[Sequence[BaseMessage],
|
| 17 |
|
| 18 |
# This is the modern way to create a robust agent with LangGraph.
|
| 19 |
-
# It automatically wires up the LLM, tools, and state into a graph.
|
| 20 |
def create_langgraph_agent():
|
| 21 |
print("Initializing LangGraphAgent...")
|
| 22 |
|
|
@@ -31,21 +34,46 @@ def create_langgraph_agent():
|
|
| 31 |
|
| 32 |
# 2. Define the Tools
|
| 33 |
tools = [DuckDuckGoSearchRun()]
|
|
|
|
| 34 |
print("Tools initialized.")
|
| 35 |
|
| 36 |
-
# 3.
|
| 37 |
-
#
|
| 38 |
-
|
| 39 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 40 |
|
| 41 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
|
| 43 |
# This function runs the agent for a single question.
|
| 44 |
def run_agent(agent_executor, question: str) -> str:
|
| 45 |
print(f"Agent received question: {question}")
|
| 46 |
try:
|
| 47 |
# We invoke the agent with the question in the correct message format
|
| 48 |
-
response = agent_executor.invoke({"messages": [(
|
| 49 |
# The final answer is in the last message of the output
|
| 50 |
final_answer = response['messages'][-1].content
|
| 51 |
except Exception as e:
|
|
@@ -55,11 +83,8 @@ def run_agent(agent_executor, question: str) -> str:
|
|
| 55 |
print(f"Agent returning answer: {final_answer}")
|
| 56 |
return str(final_answer)
|
| 57 |
|
|
|
|
| 58 |
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
| 59 |
-
"""
|
| 60 |
-
Fetches all questions, runs the LangGraphAgent on them, submits all answers,
|
| 61 |
-
and displays the results.
|
| 62 |
-
"""
|
| 63 |
space_id = os.getenv("SPACE_ID")
|
| 64 |
if not profile:
|
| 65 |
return "Please Login to Hugging Face with the button.", None
|
|
@@ -83,34 +108,6 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
| 83 |
answers_payload = []
|
| 84 |
for item in questions_data:
|
| 85 |
task_id, question_text = item.get("task_id"), item.get("question")
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
|
| 90 |
-
submit_url = f"https://agents-course-unit4-scoring.hf.space/submit"
|
| 91 |
-
try:
|
| 92 |
-
response = requests.post(submit_url, json=submission_data, timeout=120) # Increased timeout
|
| 93 |
-
response.raise_for_status()
|
| 94 |
-
result_data = response.json()
|
| 95 |
-
final_status = (
|
| 96 |
-
f"Submission Successful!\n"
|
| 97 |
-
f"User: {result_data.get('username')}\n"
|
| 98 |
-
f"Overall Score: {result_data.get('score', 'N/A')}% "
|
| 99 |
-
f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
|
| 100 |
-
f"Message: {result_data.get('message', 'No message received.')}"
|
| 101 |
-
)
|
| 102 |
-
return final_status, pd.DataFrame(answers_payload)
|
| 103 |
-
except Exception as e:
|
| 104 |
-
return f"Error during submission: {e}", pd.DataFrame(answers_payload)
|
| 105 |
-
|
| 106 |
-
# --- Gradio Interface (Unchanged) ---
|
| 107 |
-
with gr.Blocks() as demo:
|
| 108 |
-
gr.Markdown("# Agent Evaluation Runner (LangGraph Version)")
|
| 109 |
-
gr.LoginButton()
|
| 110 |
-
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
| 111 |
-
status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
|
| 112 |
-
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
| 113 |
-
run_button.click(fn=run_and_submit_all, outputs=[status_output, results_table])
|
| 114 |
-
|
| 115 |
-
if __name__ == "__main__":
|
| 116 |
-
demo.launch()
|
|
|
|
| 3 |
import requests
|
| 4 |
import pandas as pd
|
| 5 |
from typing import TypedDict, Annotated, Sequence
|
| 6 |
+
import operator
|
| 7 |
+
from langchain_core.messages import BaseMessage, HumanMessage
|
| 8 |
+
from langchain.agents import create_tool_calling_agent
|
| 9 |
+
from langchain_core.prompts import ChatPromptTemplate
|
| 10 |
from langchain_community.tools import DuckDuckGoSearchRun
|
| 11 |
from langchain_huggingface import HuggingFaceEndpoint
|
| 12 |
+
from langgraph.graph import StateGraph, END
|
| 13 |
+
from langgraph.prebuilt import ToolNode
|
| 14 |
|
| 15 |
# --- Main Application Logic ---
|
| 16 |
|
| 17 |
+
# This defines the "memory" or state of our agent.
|
| 18 |
+
# It holds the messages that make up the conversation.
|
| 19 |
class AgentState(TypedDict):
|
| 20 |
+
messages: Annotated[Sequence[BaseMessage], operator.add]
|
| 21 |
|
| 22 |
# This is the modern way to create a robust agent with LangGraph.
|
|
|
|
| 23 |
def create_langgraph_agent():
|
| 24 |
print("Initializing LangGraphAgent...")
|
| 25 |
|
|
|
|
| 34 |
|
| 35 |
# 2. Define the Tools
|
| 36 |
tools = [DuckDuckGoSearchRun()]
|
| 37 |
+
tool_node = ToolNode(tools)
|
| 38 |
print("Tools initialized.")
|
| 39 |
|
| 40 |
+
# 3. Define the agent's logic (the "agent" node)
|
| 41 |
+
# We create a prompt that tells the model how to use tools
|
| 42 |
+
prompt = ChatPromptTemplate.from_messages([
|
| 43 |
+
("system", "You are a helpful assistant. Use your tools to answer the user's questions."),
|
| 44 |
+
("placeholder", "{messages}"),
|
| 45 |
+
])
|
| 46 |
+
agent = create_tool_calling_agent(llm, tools, prompt)
|
| 47 |
+
print("Agent logic created.")
|
| 48 |
+
|
| 49 |
+
# 4. Define the Graph
|
| 50 |
+
graph = StateGraph(AgentState)
|
| 51 |
+
graph.add_node("agent", agent)
|
| 52 |
+
graph.add_node("tools", tool_node)
|
| 53 |
|
| 54 |
+
graph.set_entry_point("agent")
|
| 55 |
+
|
| 56 |
+
# This function decides where to go after the agent node: to a tool or to the end.
|
| 57 |
+
def should_continue(state):
|
| 58 |
+
last_message = state['messages'][-1]
|
| 59 |
+
if not last_message.tool_calls:
|
| 60 |
+
return END
|
| 61 |
+
return "tools"
|
| 62 |
+
|
| 63 |
+
graph.add_conditional_edges("agent", should_continue)
|
| 64 |
+
graph.add_edge("tools", "agent")
|
| 65 |
+
|
| 66 |
+
# 5. Compile the graph into a runnable app
|
| 67 |
+
app = graph.compile()
|
| 68 |
+
print("LangGraph agent compiled and ready.")
|
| 69 |
+
return app
|
| 70 |
|
| 71 |
# This function runs the agent for a single question.
|
| 72 |
def run_agent(agent_executor, question: str) -> str:
|
| 73 |
print(f"Agent received question: {question}")
|
| 74 |
try:
|
| 75 |
# We invoke the agent with the question in the correct message format
|
| 76 |
+
response = agent_executor.invoke({"messages": [HumanMessage(content=question)]})
|
| 77 |
# The final answer is in the last message of the output
|
| 78 |
final_answer = response['messages'][-1].content
|
| 79 |
except Exception as e:
|
|
|
|
| 83 |
print(f"Agent returning answer: {final_answer}")
|
| 84 |
return str(final_answer)
|
| 85 |
|
| 86 |
+
# The rest of the file remains largely the same as the original template
|
| 87 |
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 88 |
space_id = os.getenv("SPACE_ID")
|
| 89 |
if not profile:
|
| 90 |
return "Please Login to Hugging Face with the button.", None
|
|
|
|
| 108 |
answers_payload = []
|
| 109 |
for item in questions_data:
|
| 110 |
task_id, question_text = item.get("task_id"), item.get("question")
|
| 111 |
+
if task_id and question_text:
|
| 112 |
+
submitted_answer = run_agent(agent_executor, question_text)
|
| 113 |
+
answers_payload.append({"task_id": task_id, "submitted
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|