Spaces:
Sleeping
Sleeping
Update agent.py
Browse files
agent.py
CHANGED
|
@@ -1,16 +1,19 @@
|
|
| 1 |
import os
|
| 2 |
import re
|
| 3 |
import getpass
|
|
|
|
| 4 |
from typing import List, TypedDict
|
| 5 |
|
|
|
|
| 6 |
# LangChain and LangGraph components
|
| 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.utilities import PythonREPL
|
| 11 |
from langgraph.graph import StateGraph, END
|
| 12 |
from langchain_groq import ChatGroq
|
| 13 |
|
|
|
|
| 14 |
# --- Environment Setup ---
|
| 15 |
# It's recommended to set API keys as environment variables for security.
|
| 16 |
# Fallback to getpass if not set, for interactive environments.
|
|
@@ -18,10 +21,12 @@ def _set_env(var: str):
|
|
| 18 |
if not os.environ.get(var):
|
| 19 |
os.environ[var] = getpass.getpass(f"{var}: ")
|
| 20 |
|
|
|
|
| 21 |
# Ensure API keys are set from environment variables in the HF Space
|
| 22 |
_set_env("TAVILY_API_KEY")
|
| 23 |
_set_env("GROQ_API_KEY")
|
| 24 |
|
|
|
|
| 25 |
# --- Tool Definitions ---
|
| 26 |
# Initialize the Tavily search tool for web queries.
|
| 27 |
web_search_tool = TavilySearchResults(
|
|
@@ -29,9 +34,11 @@ web_search_tool = TavilySearchResults(
|
|
| 29 |
description="A search engine useful for answering questions about events, data, and general information."
|
| 30 |
)
|
| 31 |
|
|
|
|
| 32 |
# Initialize the Python REPL tool for executing code.
|
| 33 |
python_repl = PythonREPL()
|
| 34 |
|
|
|
|
| 35 |
@tool
|
| 36 |
def python_repl_tool(code: str) -> str:
|
| 37 |
"""
|
|
@@ -50,9 +57,11 @@ def python_repl_tool(code: str) -> str:
|
|
| 50 |
except Exception as e:
|
| 51 |
return f"Error during execution: {e}. Please check the code for syntax errors."
|
| 52 |
|
|
|
|
| 53 |
# Aggregate all tools into a list for the agent.
|
| 54 |
tools = [web_search_tool, python_repl_tool]
|
| 55 |
|
|
|
|
| 56 |
# --- Agent State Definition ---
|
| 57 |
class AgentState(TypedDict):
|
| 58 |
"""
|
|
@@ -61,18 +70,21 @@ class AgentState(TypedDict):
|
|
| 61 |
"""
|
| 62 |
messages: List[BaseMessage]
|
| 63 |
|
|
|
|
| 64 |
# --- Agent Graph Construction ---
|
| 65 |
# Initialize the LLM
|
| 66 |
llm = ChatGroq(model="llama3-70b-8192", temperature=0)
|
| 67 |
# Bind the tools to the LLM so it knows how to call them
|
| 68 |
llm_with_tools = llm.bind_tools(tools)
|
| 69 |
|
|
|
|
| 70 |
def call_model(state: AgentState):
|
| 71 |
"""Node that invokes the LLM with the current state."""
|
| 72 |
messages = state['messages']
|
| 73 |
response = llm_with_tools.invoke(messages)
|
| 74 |
return {"messages": [response]}
|
| 75 |
|
|
|
|
| 76 |
def call_tool(state: AgentState):
|
| 77 |
"""
|
| 78 |
Node that executes tools based on the LLM's response.
|
|
@@ -90,19 +102,23 @@ def call_tool(state: AgentState):
|
|
| 90 |
else:
|
| 91 |
output = tool_to_call.invoke(tool_call["args"])
|
| 92 |
|
| 93 |
-
tool_outputs.append(
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
|
|
|
|
|
|
| 98 |
return {"messages": tool_outputs}
|
| 99 |
|
|
|
|
| 100 |
def should_continue(state: AgentState):
|
| 101 |
"""Conditional edge that decides the next step: call a tool or end."""
|
| 102 |
if state['messages'][-1].tool_calls:
|
| 103 |
return "call_tool"
|
| 104 |
return END
|
| 105 |
|
|
|
|
| 106 |
# Define the graph structure
|
| 107 |
workflow = StateGraph(AgentState)
|
| 108 |
workflow.add_node("agent", call_model)
|
|
@@ -111,6 +127,7 @@ workflow.set_entry_point("agent")
|
|
| 111 |
workflow.add_conditional_edges("agent", should_continue)
|
| 112 |
workflow.add_edge("call_tool", "agent")
|
| 113 |
|
|
|
|
| 114 |
# Compile the graph into a runnable application
|
| 115 |
app = workflow.compile()
|
| 116 |
|
|
@@ -119,6 +136,7 @@ app = workflow.compile()
|
|
| 119 |
def solve(task: str) -> str:
|
| 120 |
"""
|
| 121 |
Executes the agent graph for a given task with enhanced error resilience.
|
|
|
|
| 122 |
"""
|
| 123 |
initial_state = {"messages": [HumanMessage(content=task)]}
|
| 124 |
try:
|
|
@@ -133,5 +151,10 @@ def solve(task: str) -> str:
|
|
| 133 |
|
| 134 |
except Exception as e:
|
| 135 |
# If any part of the app.invoke call fails, catch the exception.
|
| 136 |
-
|
| 137 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import os
|
| 2 |
import re
|
| 3 |
import getpass
|
| 4 |
+
import traceback
|
| 5 |
from typing import List, TypedDict
|
| 6 |
|
| 7 |
+
|
| 8 |
# LangChain and LangGraph components
|
| 9 |
+
from langchain_core.messages import BaseMessage, HumanMessage, ToolMessage
|
| 10 |
from langchain.tools import tool
|
| 11 |
from langchain_community.tools.tavily_search import TavilySearchResults
|
| 12 |
from langchain_experimental.utilities import PythonREPL
|
| 13 |
from langgraph.graph import StateGraph, END
|
| 14 |
from langchain_groq import ChatGroq
|
| 15 |
|
| 16 |
+
|
| 17 |
# --- Environment Setup ---
|
| 18 |
# It's recommended to set API keys as environment variables for security.
|
| 19 |
# Fallback to getpass if not set, for interactive environments.
|
|
|
|
| 21 |
if not os.environ.get(var):
|
| 22 |
os.environ[var] = getpass.getpass(f"{var}: ")
|
| 23 |
|
| 24 |
+
|
| 25 |
# Ensure API keys are set from environment variables in the HF Space
|
| 26 |
_set_env("TAVILY_API_KEY")
|
| 27 |
_set_env("GROQ_API_KEY")
|
| 28 |
|
| 29 |
+
|
| 30 |
# --- Tool Definitions ---
|
| 31 |
# Initialize the Tavily search tool for web queries.
|
| 32 |
web_search_tool = TavilySearchResults(
|
|
|
|
| 34 |
description="A search engine useful for answering questions about events, data, and general information."
|
| 35 |
)
|
| 36 |
|
| 37 |
+
|
| 38 |
# Initialize the Python REPL tool for executing code.
|
| 39 |
python_repl = PythonREPL()
|
| 40 |
|
| 41 |
+
|
| 42 |
@tool
|
| 43 |
def python_repl_tool(code: str) -> str:
|
| 44 |
"""
|
|
|
|
| 57 |
except Exception as e:
|
| 58 |
return f"Error during execution: {e}. Please check the code for syntax errors."
|
| 59 |
|
| 60 |
+
|
| 61 |
# Aggregate all tools into a list for the agent.
|
| 62 |
tools = [web_search_tool, python_repl_tool]
|
| 63 |
|
| 64 |
+
|
| 65 |
# --- Agent State Definition ---
|
| 66 |
class AgentState(TypedDict):
|
| 67 |
"""
|
|
|
|
| 70 |
"""
|
| 71 |
messages: List[BaseMessage]
|
| 72 |
|
| 73 |
+
|
| 74 |
# --- Agent Graph Construction ---
|
| 75 |
# Initialize the LLM
|
| 76 |
llm = ChatGroq(model="llama3-70b-8192", temperature=0)
|
| 77 |
# Bind the tools to the LLM so it knows how to call them
|
| 78 |
llm_with_tools = llm.bind_tools(tools)
|
| 79 |
|
| 80 |
+
|
| 81 |
def call_model(state: AgentState):
|
| 82 |
"""Node that invokes the LLM with the current state."""
|
| 83 |
messages = state['messages']
|
| 84 |
response = llm_with_tools.invoke(messages)
|
| 85 |
return {"messages": [response]}
|
| 86 |
|
| 87 |
+
|
| 88 |
def call_tool(state: AgentState):
|
| 89 |
"""
|
| 90 |
Node that executes tools based on the LLM's response.
|
|
|
|
| 102 |
else:
|
| 103 |
output = tool_to_call.invoke(tool_call["args"])
|
| 104 |
|
| 105 |
+
tool_outputs.append(
|
| 106 |
+
ToolMessage(
|
| 107 |
+
tool_call_id=tool_call["id"],
|
| 108 |
+
content=str(output),
|
| 109 |
+
name=tool_name
|
| 110 |
+
)
|
| 111 |
+
)
|
| 112 |
return {"messages": tool_outputs}
|
| 113 |
|
| 114 |
+
|
| 115 |
def should_continue(state: AgentState):
|
| 116 |
"""Conditional edge that decides the next step: call a tool or end."""
|
| 117 |
if state['messages'][-1].tool_calls:
|
| 118 |
return "call_tool"
|
| 119 |
return END
|
| 120 |
|
| 121 |
+
|
| 122 |
# Define the graph structure
|
| 123 |
workflow = StateGraph(AgentState)
|
| 124 |
workflow.add_node("agent", call_model)
|
|
|
|
| 127 |
workflow.add_conditional_edges("agent", should_continue)
|
| 128 |
workflow.add_edge("call_tool", "agent")
|
| 129 |
|
| 130 |
+
|
| 131 |
# Compile the graph into a runnable application
|
| 132 |
app = workflow.compile()
|
| 133 |
|
|
|
|
| 136 |
def solve(task: str) -> str:
|
| 137 |
"""
|
| 138 |
Executes the agent graph for a given task with enhanced error resilience.
|
| 139 |
+
If the agent fails, it returns the full exception traceback for debugging.
|
| 140 |
"""
|
| 141 |
initial_state = {"messages": [HumanMessage(content=task)]}
|
| 142 |
try:
|
|
|
|
| 151 |
|
| 152 |
except Exception as e:
|
| 153 |
# If any part of the app.invoke call fails, catch the exception.
|
| 154 |
+
# Format the full traceback into a string for detailed debugging.
|
| 155 |
+
error_details = traceback.format_exc()
|
| 156 |
+
print(f"AGENT_ERROR: An exception occurred during execution:\n{error_details}")
|
| 157 |
+
|
| 158 |
+
# Return the full traceback as the answer. This ensures a valid string
|
| 159 |
+
# output is always produced, aiding in remote debugging.
|
| 160 |
+
return f"An error occurred during agent execution. Details:\n{error_details}"
|