mrhenu commited on
Commit
635f2c2
·
verified ·
1 Parent(s): 973dd42

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +16 -24
app.py CHANGED
@@ -5,42 +5,42 @@ 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.tools import tool
9
- from langchain_community.tools.tavily_search import TavilySearchResults
10
  from langchain_experimental.tools import PythonREPLTool
11
- from langchain_community.tools.youtube import YouTubeSearchTool
 
12
  from langchain_openai import ChatOpenAI
13
  from langgraph.graph import StateGraph, END
14
  from langgraph.prebuilt import ToolNode, tools_condition
15
 
16
  # --- Main Application Logic ---
17
 
18
- # Agentin muisti
19
  class AgentState(TypedDict):
20
  messages: Annotated[Sequence[BaseMessage], operator.add]
21
 
22
- # Agentin rakentajafunktio
23
  def create_langgraph_agent():
24
  print("Initializing Advanced LangGraph Agent...")
25
 
26
- # 1. Kielimalli (GPT-4o on paras valinta)
27
  llm = ChatOpenAI(model="gpt-4o", temperature=0)
28
 
29
- # 2. Työkalut: Lisätty PythonREPL ja YouTube
30
  tools = [TavilySearchResults(max_results=3), PythonREPLTool(), YouTubeSearchTool()]
31
  llm_with_tools = llm.bind_tools(tools)
32
  print("LLM and tools initialized.")
33
 
34
- # 3. Agentin solmu (kutsuu kielimallia)
35
  def agent_node(state):
36
  print("Calling agent node...")
37
  return {"messages": [llm_with_tools.invoke(state["messages"])]}
38
 
39
- # 4. Työkalusolmu
40
  tool_node = ToolNode(tools)
41
  print("Graph nodes defined.")
42
 
43
- # 5. Graafin määritys
44
  graph = StateGraph(AgentState)
45
  graph.add_node("agent", agent_node)
46
  graph.add_node("tools", tool_node)
@@ -48,32 +48,25 @@ def create_langgraph_agent():
48
  graph.add_conditional_edges("agent", tools_condition)
49
  graph.add_edge("tools", "agent")
50
 
51
- # 6. Graafin kääntäminen ja turvarajan asettaminen
52
- app = graph.compile(recursion_limit=15) # Nostetaan limiittiä monimutkaisempia tehtäviä varten
53
  print("LangGraph agent compiled and ready.")
54
  return app
55
 
56
- # Agentin suoritusfunktio
57
  def run_agent(agent_executor, question: str) -> str:
58
  print(f"Agent received question: {question}")
59
  final_answer = ""
60
  try:
61
  response = agent_executor.invoke(
62
  {"messages": [HumanMessage(content=question)]},
63
- # Lisätään konfiguraatio, joka kertoo mille solmulle aikaraja asetetaan
64
  config={"recursion_limit": 15}
65
  )
66
-
67
- # Otetaan vastaus viimeisestä viestistä
68
  raw_answer = response['messages'][-1].content
69
-
70
- # Yritetään poimia vain "FINAL ANSWER" -osa, jos se on olemassa
71
- # Tämä parantaa vastausten tarkkuutta.
72
  if "FINAL ANSWER:" in raw_answer:
73
  final_answer = raw_answer.split("FINAL ANSWER:")[-1].strip()
74
  else:
75
  final_answer = raw_answer
76
-
77
  except Exception as e:
78
  print(f"Error during agent execution: {e}")
79
  final_answer = f"Error: Agent failed to execute. {e}"
@@ -81,14 +74,13 @@ def run_agent(agent_executor, question: str) -> str:
81
  print(f"Agent returning answer: {final_answer}")
82
  return str(final_answer)
83
 
84
- # Evaluaation ajaminen (kuten ennenkin)
85
  def run_and_submit_all(profile: gr.OAuthProfile | None):
86
  space_id = os.getenv("SPACE_ID")
87
  if not profile:
88
  return "Please Login to Hugging Face with the button.", None
89
  username = f"{profile.username}"
90
 
91
- # API-avainten tarkistus
92
  if not os.getenv("TAVILY_API_KEY") or not os.getenv("OPENAI_API_KEY"):
93
  return "One or more API keys (TAVILY_API_KEY, OPENAI_API_KEY) are not set.", None
94
 
@@ -116,7 +108,7 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
116
  submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
117
  submit_url = f"https://agents-course-unit4-scoring.hf.space/submit"
118
  try:
119
- response = requests.post(submit_url, json=submission_data, timeout=240) # Pidennetty timeout
120
  response.raise_for_status()
121
  result_data = response.json()
122
  final_status = (
@@ -130,7 +122,7 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
130
  except Exception as e:
131
  return f"Error during submission: {e}", pd.DataFrame(answers_payload)
132
 
133
- # Gradio-käyttöliittymä
134
  with gr.Blocks() as demo:
135
  gr.Markdown("# Agent Evaluation Runner (Advanced Tools)")
136
  gr.LoginButton()
 
5
  from typing import TypedDict, Annotated, Sequence
6
  import operator
7
  from langchain_core.messages import BaseMessage, HumanMessage
8
+ from langchain.agents import AgentExecutor
 
9
  from langchain_experimental.tools import PythonREPLTool
10
+ from langchain_community.tools.Youtube import YouTubeSearchTool # THIS IS THE CORRECTED LINE
11
+ from langchain_community.tools.tavily_search import TavilySearchResults
12
  from langchain_openai import ChatOpenAI
13
  from langgraph.graph import StateGraph, END
14
  from langgraph.prebuilt import ToolNode, tools_condition
15
 
16
  # --- Main Application Logic ---
17
 
18
+ # Agent's memory
19
  class AgentState(TypedDict):
20
  messages: Annotated[Sequence[BaseMessage], operator.add]
21
 
22
+ # Agent builder function
23
  def create_langgraph_agent():
24
  print("Initializing Advanced LangGraph Agent...")
25
 
26
+ # 1. Language Model (GPT-4o is the best choice)
27
  llm = ChatOpenAI(model="gpt-4o", temperature=0)
28
 
29
+ # 2. Tools: Tavily, PythonREPL, and YouTube
30
  tools = [TavilySearchResults(max_results=3), PythonREPLTool(), YouTubeSearchTool()]
31
  llm_with_tools = llm.bind_tools(tools)
32
  print("LLM and tools initialized.")
33
 
34
+ # 3. Agent node (calls the language model)
35
  def agent_node(state):
36
  print("Calling agent node...")
37
  return {"messages": [llm_with_tools.invoke(state["messages"])]}
38
 
39
+ # 4. Tool node
40
  tool_node = ToolNode(tools)
41
  print("Graph nodes defined.")
42
 
43
+ # 5. Graph definition
44
  graph = StateGraph(AgentState)
45
  graph.add_node("agent", agent_node)
46
  graph.add_node("tools", tool_node)
 
48
  graph.add_conditional_edges("agent", tools_condition)
49
  graph.add_edge("tools", "agent")
50
 
51
+ # 6. Compile graph and set safety limit
52
+ app = graph.compile(recursion_limit=15)
53
  print("LangGraph agent compiled and ready.")
54
  return app
55
 
56
+ # Agent execution function
57
  def run_agent(agent_executor, question: str) -> str:
58
  print(f"Agent received question: {question}")
59
  final_answer = ""
60
  try:
61
  response = agent_executor.invoke(
62
  {"messages": [HumanMessage(content=question)]},
 
63
  config={"recursion_limit": 15}
64
  )
 
 
65
  raw_answer = response['messages'][-1].content
 
 
 
66
  if "FINAL ANSWER:" in raw_answer:
67
  final_answer = raw_answer.split("FINAL ANSWER:")[-1].strip()
68
  else:
69
  final_answer = raw_answer
 
70
  except Exception as e:
71
  print(f"Error during agent execution: {e}")
72
  final_answer = f"Error: Agent failed to execute. {e}"
 
74
  print(f"Agent returning answer: {final_answer}")
75
  return str(final_answer)
76
 
77
+ # Evaluation runner
78
  def run_and_submit_all(profile: gr.OAuthProfile | None):
79
  space_id = os.getenv("SPACE_ID")
80
  if not profile:
81
  return "Please Login to Hugging Face with the button.", None
82
  username = f"{profile.username}"
83
 
 
84
  if not os.getenv("TAVILY_API_KEY") or not os.getenv("OPENAI_API_KEY"):
85
  return "One or more API keys (TAVILY_API_KEY, OPENAI_API_KEY) are not set.", None
86
 
 
108
  submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
109
  submit_url = f"https://agents-course-unit4-scoring.hf.space/submit"
110
  try:
111
+ response = requests.post(submit_url, json=submission_data, timeout=240)
112
  response.raise_for_status()
113
  result_data = response.json()
114
  final_status = (
 
122
  except Exception as e:
123
  return f"Error during submission: {e}", pd.DataFrame(answers_payload)
124
 
125
+ # Gradio Interface
126
  with gr.Blocks() as demo:
127
  gr.Markdown("# Agent Evaluation Runner (Advanced Tools)")
128
  gr.LoginButton()