mrhenu commited on
Commit
80eae18
·
verified ·
1 Parent(s): 09238db

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +21 -23
app.py CHANGED
@@ -5,24 +5,22 @@ 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
- from langchain import hub
15
 
16
  # --- Main Application Logic ---
17
 
18
  # This defines the "memory" or state of our agent.
19
- # It holds the messages that make up the conversation.
20
  class AgentState(TypedDict):
21
  messages: Annotated[Sequence[BaseMessage], operator.add]
22
 
23
- # This is the modern way to create a robust agent with LangGraph.
24
- def create_langgraph_agent():
25
- print("Initializing LangGraphAgent...")
26
 
27
  # 1. Set up the LLM (The "Brain")
28
  llm = HuggingFaceEndpoint(
@@ -38,41 +36,41 @@ def create_langgraph_agent():
38
  tool_node = ToolNode(tools)
39
  print("Tools initialized.")
40
 
41
- # 3. Define the agent's logic (the "agent" node)
42
- # We create a prompt that tells the model how to use tools
43
- prompt = hub.pull("hwchase17/openai-tools-agent")
44
- agent = create_tool_calling_agent(llm, tools, prompt)
 
 
 
45
  print("Agent logic created.")
46
 
47
- # 4. Define the Graph
48
  graph = StateGraph(AgentState)
49
- graph.add_node("agent", agent)
50
  graph.add_node("tools", tool_node)
51
 
52
  graph.set_entry_point("agent")
53
 
54
- # This function decides where to go after the agent node: to a tool or to the end.
55
  def should_continue(state):
56
  last_message = state['messages'][-1]
57
- if not last_message.tool_calls:
58
  return END
59
  return "tools"
60
 
61
  graph.add_conditional_edges("agent", should_continue)
62
  graph.add_edge("tools", "agent")
63
 
64
- # 5. Compile the graph into a runnable app
65
  app = graph.compile()
66
  print("LangGraph agent compiled and ready.")
67
  return app
68
 
69
  # This function runs the agent for a single question.
70
- def run_agent(agent_executor, question: str) -> str:
71
  print(f"Agent received question: {question}")
72
  try:
73
- # We invoke the agent with the question in the correct message format
74
  response = agent_executor.invoke({"messages": [HumanMessage(content=question)]})
75
- # The final answer is in the last message of the output
76
  final_answer = response['messages'][-1].content
77
  except Exception as e:
78
  print(f"Error during agent execution: {e}")
@@ -89,7 +87,7 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
89
  username = f"{profile.username}"
90
 
91
  try:
92
- agent_executor = create_langgraph_agent()
93
  except Exception as e:
94
  return f"Error initializing agent: {e}", None
95
 
@@ -107,7 +105,7 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
107
  for item in questions_data:
108
  task_id, question_text = item.get("task_id"), item.get("question")
109
  if task_id and question_text:
110
- submitted_answer = run_agent(agent_executor, question_text)
111
  answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
112
 
113
  submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
@@ -128,7 +126,7 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
128
  return f"Error during submission: {e}", pd.DataFrame(answers_payload)
129
 
130
  with gr.Blocks() as demo:
131
- gr.Markdown("# Agent Evaluation Runner (LangGraph Final Version)")
132
  gr.LoginButton()
133
  run_button = gr.Button("Run Evaluation & Submit All Answers")
134
  status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
@@ -136,4 +134,4 @@ with gr.Blocks() as demo:
136
  run_button.click(fn=run_and_submit_all, outputs=[status_output, results_table])
137
 
138
  if __name__ == "__main__":
139
- demo.launch()
 
5
  from typing import TypedDict, Annotated, Sequence
6
  import operator
7
  from langchain_core.messages import BaseMessage, HumanMessage
8
+ from langchain.agents import AgentExecutor, create_react_agent
9
+ from langchain import hub
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
  class AgentState(TypedDict):
19
  messages: Annotated[Sequence[BaseMessage], operator.add]
20
 
21
+ # This function builds our agent using the standard ReAct framework
22
+ def create_agent():
23
+ print("Initializing ReAct Agent...")
24
 
25
  # 1. Set up the LLM (The "Brain")
26
  llm = HuggingFaceEndpoint(
 
36
  tool_node = ToolNode(tools)
37
  print("Tools initialized.")
38
 
39
+ # 3. Get the ReAct Prompt Template
40
+ # This prompt is designed to work with create_react_agent
41
+ prompt = hub.pull("hwchase17/react-chat")
42
+ print("Prompt template pulled: hwchase17/react-chat")
43
+
44
+ # 4. Create the agent's logic
45
+ agent_runnable = create_react_agent(llm, tools, prompt)
46
  print("Agent logic created.")
47
 
48
+ # 5. Define the Graph
49
  graph = StateGraph(AgentState)
50
+ graph.add_node("agent", lambda state: {"messages": agent_runnable.invoke(state)['messages']})
51
  graph.add_node("tools", tool_node)
52
 
53
  graph.set_entry_point("agent")
54
 
 
55
  def should_continue(state):
56
  last_message = state['messages'][-1]
57
+ if not hasattr(last_message, 'tool_calls') or not last_message.tool_calls:
58
  return END
59
  return "tools"
60
 
61
  graph.add_conditional_edges("agent", should_continue)
62
  graph.add_edge("tools", "agent")
63
 
64
+ # 6. Compile the graph into a runnable app
65
  app = graph.compile()
66
  print("LangGraph agent compiled and ready.")
67
  return app
68
 
69
  # This function runs the agent for a single question.
70
+ def run_agent_for_task(agent_executor, question: str) -> str:
71
  print(f"Agent received question: {question}")
72
  try:
 
73
  response = agent_executor.invoke({"messages": [HumanMessage(content=question)]})
 
74
  final_answer = response['messages'][-1].content
75
  except Exception as e:
76
  print(f"Error during agent execution: {e}")
 
87
  username = f"{profile.username}"
88
 
89
  try:
90
+ agent_executor = create_agent()
91
  except Exception as e:
92
  return f"Error initializing agent: {e}", None
93
 
 
105
  for item in questions_data:
106
  task_id, question_text = item.get("task_id"), item.get("question")
107
  if task_id and question_text:
108
+ submitted_answer = run_agent_for_task(agent_executor, question_text)
109
  answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
110
 
111
  submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
 
126
  return f"Error during submission: {e}", pd.DataFrame(answers_payload)
127
 
128
  with gr.Blocks() as demo:
129
+ gr.Markdown("# Agent Evaluation Runner (Final LangGraph Version)")
130
  gr.LoginButton()
131
  run_button = gr.Button("Run Evaluation & Submit All Answers")
132
  status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
 
134
  run_button.click(fn=run_and_submit_all, outputs=[status_output, results_table])
135
 
136
  if __name__ == "__main__":
137
+ demo.launch()