Spaces:
Sleeping
Sleeping
Delete agent.py
Browse files
agent.py
DELETED
|
@@ -1,132 +0,0 @@
|
|
| 1 |
-
import os
|
| 2 |
-
import re
|
| 3 |
-
import traceback
|
| 4 |
-
from typing import List, TypedDict
|
| 5 |
-
|
| 6 |
-
# LangChain and LangGraph components
|
| 7 |
-
from langchain_core.messages import BaseMessage, HumanMessage, ToolMessage
|
| 8 |
-
from langchain_openai import ChatOpenAI
|
| 9 |
-
from langchain.tools import tool
|
| 10 |
-
from langchain_community.tools.tavily_search import TavilySearchResults
|
| 11 |
-
from langchain_tavily import TavilySearch # CORRECTED IMPORT
|
| 12 |
-
from langchain_experimental.utilities import PythonREPL
|
| 13 |
-
from langgraph.graph import StateGraph, END
|
| 14 |
-
|
| 15 |
-
# --- Tool Definitions ---
|
| 16 |
-
# These are safe to define at the module level as they don't require API keys on initialization.
|
| 17 |
-
web_search_tool = TavilySearchResults(
|
| 18 |
-
max_results=3,
|
| 19 |
-
description="A search engine useful for answering questions about events, data, and general information."
|
| 20 |
-
)
|
| 21 |
-
|
| 22 |
-
python_repl = PythonREPL()
|
| 23 |
-
|
| 24 |
-
@tool
|
| 25 |
-
def python_repl_tool(code: str) -> str:
|
| 26 |
-
"""
|
| 27 |
-
Executes Python code in a REPL environment and returns the output.
|
| 28 |
-
- The code should be a valid Python script.
|
| 29 |
-
- It is sandboxed, so it cannot access the local filesystem directly.
|
| 30 |
-
- Use this for calculations, data manipulation, or any task that can be solved with Python code.
|
| 31 |
-
- Ensure the code is passed as a single string.
|
| 32 |
-
"""
|
| 33 |
-
try:
|
| 34 |
-
# Sanitize input by removing common markdown formatting
|
| 35 |
-
if code.strip().startswith("```python"):
|
| 36 |
-
code = code.strip()[9:-3].strip()
|
| 37 |
-
result = python_repl.run(code)
|
| 38 |
-
return f"Execution successful. Result:\n{result}"
|
| 39 |
-
except Exception as e:
|
| 40 |
-
return f"Error during execution: {e}. Please check the code for syntax errors."
|
| 41 |
-
|
| 42 |
-
# Aggregate all tools into a list for the agent.
|
| 43 |
-
tools = [web_search_tool, python_repl_tool]
|
| 44 |
-
|
| 45 |
-
# --- Agent State Definition ---
|
| 46 |
-
class AgentState(TypedDict):
|
| 47 |
-
"""
|
| 48 |
-
Defines the state of the agent, which is a list of messages.
|
| 49 |
-
This state is passed between nodes in the graph.
|
| 50 |
-
"""
|
| 51 |
-
messages: List[BaseMessage]
|
| 52 |
-
|
| 53 |
-
# --- Main Agent Execution Function ---
|
| 54 |
-
def solve(task: str) -> str:
|
| 55 |
-
"""
|
| 56 |
-
Initializes and executes the agent graph for a given task.
|
| 57 |
-
This function handles API key validation and graph setup at runtime,
|
| 58 |
-
preventing application startup crashes if keys are not configured.
|
| 59 |
-
"""
|
| 60 |
-
# **FIX**: Validate API keys at runtime, not at module import.
|
| 61 |
-
if not os.environ.get("OPENAI_API_KEY") or not os.environ.get("TAVILY_API_KEY"):
|
| 62 |
-
return "Error: `OPENAI_API_KEY` and `TAVILY_API_KEY` must be set as environment variables."
|
| 63 |
-
|
| 64 |
-
# --- Agent Graph Construction (Runtime) ---
|
| 65 |
-
# **MIGRATION**: Initialize the OpenAI LLM.
|
| 66 |
-
llm = ChatOpenAI(model="gpt-4-turbo", temperature=0)
|
| 67 |
-
llm_with_tools = llm.bind_tools(tools)
|
| 68 |
-
|
| 69 |
-
def call_model(state: AgentState):
|
| 70 |
-
"""Node that invokes the LLM with the current state."""
|
| 71 |
-
messages = state['messages']
|
| 72 |
-
response = llm_with_tools.invoke(messages)
|
| 73 |
-
return {"messages": [response]}
|
| 74 |
-
|
| 75 |
-
def call_tool(state: AgentState):
|
| 76 |
-
"""
|
| 77 |
-
Node that executes tools based on the LLM's response.
|
| 78 |
-
It parses tool calls from the last message and runs them.
|
| 79 |
-
"""
|
| 80 |
-
last_message = state['messages'][-1]
|
| 81 |
-
tool_outputs = []
|
| 82 |
-
for tool_call in last_message.tool_calls:
|
| 83 |
-
tool_name = tool_call["name"]
|
| 84 |
-
tool_to_call = next((t for t in tools if t.name == tool_name), None)
|
| 85 |
-
if not tool_to_call:
|
| 86 |
-
output = f"Error: Tool '{tool_name}' not found."
|
| 87 |
-
else:
|
| 88 |
-
output = tool_to_call.invoke(tool_call["args"])
|
| 89 |
-
tool_outputs.append(
|
| 90 |
-
ToolMessage(
|
| 91 |
-
tool_call_id=tool_call["id"],
|
| 92 |
-
content=str(output),
|
| 93 |
-
name=tool_name
|
| 94 |
-
)
|
| 95 |
-
)
|
| 96 |
-
return {"messages": tool_outputs}
|
| 97 |
-
|
| 98 |
-
def should_continue(state: AgentState):
|
| 99 |
-
"""Conditional edge that decides the next step: call a tool or end."""
|
| 100 |
-
if state['messages'][-1].tool_calls:
|
| 101 |
-
return "call_tool"
|
| 102 |
-
return END
|
| 103 |
-
|
| 104 |
-
# Define the graph structure
|
| 105 |
-
workflow = StateGraph(AgentState)
|
| 106 |
-
workflow.add_node("agent", call_model)
|
| 107 |
-
workflow.add_node("call_tool", call_tool)
|
| 108 |
-
workflow.set_entry_point("agent")
|
| 109 |
-
workflow.add_conditional_edges("agent", should_continue)
|
| 110 |
-
workflow.add_edge("call_tool", "agent")
|
| 111 |
-
|
| 112 |
-
# Compile the graph into a runnable application
|
| 113 |
-
app = workflow.compile()
|
| 114 |
-
|
| 115 |
-
# --- Execute the Graph ---
|
| 116 |
-
try:
|
| 117 |
-
initial_state = {"messages": [HumanMessage(content=task)]}
|
| 118 |
-
# Invoke the agent graph with the initial state.
|
| 119 |
-
final_state = app.invoke(initial_state, {"recursion_limit": 25})
|
| 120 |
-
# Extract the final answer from the last message in the state.
|
| 121 |
-
final_message = final_state["messages"][-1]
|
| 122 |
-
final_answer = final_message.content.strip()
|
| 123 |
-
return final_answer
|
| 124 |
-
except Exception as e:
|
| 125 |
-
# If any part of the app.invoke call fails, catch the exception.
|
| 126 |
-
# Format the full traceback into a string for detailed debugging.
|
| 127 |
-
error_details = traceback.format_exc()
|
| 128 |
-
print(f"AGENT_ERROR: An exception occurred during execution:\n{error_details}")
|
| 129 |
-
|
| 130 |
-
# Return the full traceback as the answer. This ensures a valid string
|
| 131 |
-
# output is always produced, aiding in remote debugging.
|
| 132 |
-
return f"An error occurred during agent execution. Details:\n{error_details}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|