Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -9,10 +9,6 @@ from langchain.agents import AgentExecutor
|
|
| 9 |
from langchain_experimental.tools import PythonREPLTool
|
| 10 |
from langchain_community.tools.youtube.search import YouTubeSearchTool
|
| 11 |
from langchain_community.tools.tavily_search import TavilySearchResults
|
| 12 |
-
|
| 13 |
-
# (Optional) Tiedostohallinnan työkalut
|
| 14 |
-
|
| 15 |
-
# LLM
|
| 16 |
from langchain_openai import ChatOpenAI
|
| 17 |
from langgraph.graph import StateGraph, END
|
| 18 |
from langgraph.prebuilt import ToolNode, tools_condition
|
|
@@ -26,7 +22,7 @@ class AgentState(TypedDict):
|
|
| 26 |
# Agentin rakentajafunktio
|
| 27 |
def create_langgraph_agent():
|
| 28 |
print("Initializing Advanced LangGraph Agent...")
|
| 29 |
-
|
| 30 |
# 1. System prompt GAIA-tyyliin
|
| 31 |
system_prompt = """
|
| 32 |
You are a general AI assistant. I will ask you a question. Report your thoughts, and finish your answer with the following template:
|
|
@@ -39,15 +35,14 @@ If you are asked for a comma separated list, apply the above rules depending on
|
|
| 39 |
"""
|
| 40 |
llm = ChatOpenAI(model="gpt-4o", temperature=0, system_message=system_prompt)
|
| 41 |
|
| 42 |
-
# 2.
|
| 43 |
tools = [
|
| 44 |
TavilySearchResults(max_results=3),
|
| 45 |
PythonREPLTool(),
|
| 46 |
YouTubeSearchTool(),
|
| 47 |
]
|
| 48 |
|
| 49 |
-
# 3.
|
| 50 |
-
# Playwright: yritetään lisätä, jos riippuvuus saatavilla ja selaimet asennettu
|
| 51 |
try:
|
| 52 |
from langchain_community.tools.playwright.utils import create_sync_playwright_browser
|
| 53 |
from langchain_community.agent_toolkits.playwright.toolkit import PlayWrightBrowserToolkit
|
|
@@ -59,28 +54,29 @@ If you are asked for a comma separated list, apply the above rules depending on
|
|
| 59 |
except Exception as e:
|
| 60 |
print("Playwright not available, skipping browser tools:", e)
|
| 61 |
|
| 62 |
-
#
|
| 63 |
try:
|
| 64 |
from langchain_community.agent_toolkits.file_management.toolkit import FileManagementToolkit
|
| 65 |
file_toolkit = FileManagementToolkit(root_dir=".")
|
| 66 |
tools.extend(file_toolkit.get_tools())
|
|
|
|
| 67 |
except Exception as e:
|
| 68 |
-
print("FileManagement toolkit unavailable:", e)
|
| 69 |
-
tools.extend(file_toolkit.get_tools())
|
| 70 |
|
|
|
|
| 71 |
llm_with_tools = llm.bind_tools(tools)
|
| 72 |
print("LLM and tools initialized.")
|
| 73 |
|
| 74 |
-
#
|
| 75 |
def agent_node(state):
|
| 76 |
print("Calling agent node...")
|
| 77 |
return {"messages": [llm_with_tools.invoke(state["messages"])]}
|
| 78 |
-
|
| 79 |
-
#
|
| 80 |
tool_node = ToolNode(tools)
|
| 81 |
print("Graph nodes defined.")
|
| 82 |
|
| 83 |
-
#
|
| 84 |
graph = StateGraph(AgentState)
|
| 85 |
graph.add_node("agent", agent_node)
|
| 86 |
graph.add_node("tools", tool_node)
|
|
@@ -88,7 +84,7 @@ If you are asked for a comma separated list, apply the above rules depending on
|
|
| 88 |
graph.add_conditional_edges("agent", tools_condition)
|
| 89 |
graph.add_edge("tools", "agent")
|
| 90 |
|
| 91 |
-
#
|
| 92 |
app = graph.compile() # rekursion raja määritellään invoke-kutsussa
|
| 93 |
print("LangGraph agent compiled and ready.")
|
| 94 |
return app
|
|
@@ -110,7 +106,7 @@ def run_agent(agent_executor, question: str) -> str:
|
|
| 110 |
except Exception as e:
|
| 111 |
print(f"Error during agent execution: {e}")
|
| 112 |
final_answer = f"Error: Agent failed to execute. {e}"
|
| 113 |
-
|
| 114 |
print(f"Agent returning answer: {final_answer}")
|
| 115 |
return str(final_answer)
|
| 116 |
|
|
@@ -120,15 +116,15 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
| 120 |
if not profile:
|
| 121 |
return "Please Login to Hugging Face with the button.", None
|
| 122 |
username = f"{profile.username}"
|
| 123 |
-
|
| 124 |
if not os.getenv("TAVILY_API_KEY") or not os.getenv("OPENAI_API_KEY"):
|
| 125 |
-
|
| 126 |
|
| 127 |
try:
|
| 128 |
agent_executor = create_langgraph_agent()
|
| 129 |
except Exception as e:
|
| 130 |
return f"Error initializing agent: {e}", None
|
| 131 |
-
|
| 132 |
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
| 133 |
questions_url = f"https://agents-course-unit4-scoring.hf.space/questions"
|
| 134 |
try:
|
|
@@ -156,7 +152,7 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
| 156 |
f"User: {result_data.get('username')}\n"
|
| 157 |
f"Overall Score: {result_data.get('score', 'N/A')}% "
|
| 158 |
f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
|
| 159 |
-
f"Message: {result_data.get('message', 'No message received.')}"
|
| 160 |
)
|
| 161 |
return final_status, pd.DataFrame(answers_payload)
|
| 162 |
except Exception as e:
|
|
|
|
| 9 |
from langchain_experimental.tools import PythonREPLTool
|
| 10 |
from langchain_community.tools.youtube.search import YouTubeSearchTool
|
| 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
|
|
|
|
| 22 |
# Agentin rakentajafunktio
|
| 23 |
def create_langgraph_agent():
|
| 24 |
print("Initializing Advanced LangGraph Agent...")
|
| 25 |
+
|
| 26 |
# 1. System prompt GAIA-tyyliin
|
| 27 |
system_prompt = """
|
| 28 |
You are a general AI assistant. I will ask you a question. Report your thoughts, and finish your answer with the following template:
|
|
|
|
| 35 |
"""
|
| 36 |
llm = ChatOpenAI(model="gpt-4o", temperature=0, system_message=system_prompt)
|
| 37 |
|
| 38 |
+
# 2. Perustyökalut: Tavily, PythonREPL, YouTube
|
| 39 |
tools = [
|
| 40 |
TavilySearchResults(max_results=3),
|
| 41 |
PythonREPLTool(),
|
| 42 |
YouTubeSearchTool(),
|
| 43 |
]
|
| 44 |
|
| 45 |
+
# 3. Valinnainen Playwright-selain toolkit
|
|
|
|
| 46 |
try:
|
| 47 |
from langchain_community.tools.playwright.utils import create_sync_playwright_browser
|
| 48 |
from langchain_community.agent_toolkits.playwright.toolkit import PlayWrightBrowserToolkit
|
|
|
|
| 54 |
except Exception as e:
|
| 55 |
print("Playwright not available, skipping browser tools:", e)
|
| 56 |
|
| 57 |
+
# 4. Valinnainen FileManagement toolkit
|
| 58 |
try:
|
| 59 |
from langchain_community.agent_toolkits.file_management.toolkit import FileManagementToolkit
|
| 60 |
file_toolkit = FileManagementToolkit(root_dir=".")
|
| 61 |
tools.extend(file_toolkit.get_tools())
|
| 62 |
+
print("FileManagement tools loaded.")
|
| 63 |
except Exception as e:
|
| 64 |
+
print("FileManagement toolkit unavailable:", e)
|
|
|
|
| 65 |
|
| 66 |
+
# Bind tools to LLM
|
| 67 |
llm_with_tools = llm.bind_tools(tools)
|
| 68 |
print("LLM and tools initialized.")
|
| 69 |
|
| 70 |
+
# 5. Agentin solmu (kutsuu kielimallia)
|
| 71 |
def agent_node(state):
|
| 72 |
print("Calling agent node...")
|
| 73 |
return {"messages": [llm_with_tools.invoke(state["messages"])]}
|
| 74 |
+
|
| 75 |
+
# 6. Työkalusolmu
|
| 76 |
tool_node = ToolNode(tools)
|
| 77 |
print("Graph nodes defined.")
|
| 78 |
|
| 79 |
+
# 7. Graafin määritys
|
| 80 |
graph = StateGraph(AgentState)
|
| 81 |
graph.add_node("agent", agent_node)
|
| 82 |
graph.add_node("tools", tool_node)
|
|
|
|
| 84 |
graph.add_conditional_edges("agent", tools_condition)
|
| 85 |
graph.add_edge("tools", "agent")
|
| 86 |
|
| 87 |
+
# 8. Graafin kääntäminen
|
| 88 |
app = graph.compile() # rekursion raja määritellään invoke-kutsussa
|
| 89 |
print("LangGraph agent compiled and ready.")
|
| 90 |
return app
|
|
|
|
| 106 |
except Exception as e:
|
| 107 |
print(f"Error during agent execution: {e}")
|
| 108 |
final_answer = f"Error: Agent failed to execute. {e}"
|
| 109 |
+
|
| 110 |
print(f"Agent returning answer: {final_answer}")
|
| 111 |
return str(final_answer)
|
| 112 |
|
|
|
|
| 116 |
if not profile:
|
| 117 |
return "Please Login to Hugging Face with the button.", None
|
| 118 |
username = f"{profile.username}"
|
| 119 |
+
|
| 120 |
if not os.getenv("TAVILY_API_KEY") or not os.getenv("OPENAI_API_KEY"):
|
| 121 |
+
return "One or more API keys (TAVILY_API_KEY, OPENAI_API_KEY) are not set.", None
|
| 122 |
|
| 123 |
try:
|
| 124 |
agent_executor = create_langgraph_agent()
|
| 125 |
except Exception as e:
|
| 126 |
return f"Error initializing agent: {e}", None
|
| 127 |
+
|
| 128 |
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
| 129 |
questions_url = f"https://agents-course-unit4-scoring.hf.space/questions"
|
| 130 |
try:
|
|
|
|
| 152 |
f"User: {result_data.get('username')}\n"
|
| 153 |
f"Overall Score: {result_data.get('score', 'N/A')}% "
|
| 154 |
f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
|
| 155 |
+
f"Message: {result_data.get('message', 'No message received.') }"
|
| 156 |
)
|
| 157 |
return final_status, pd.DataFrame(answers_payload)
|
| 158 |
except Exception as e:
|