Spaces:
Sleeping
Sleeping
Update agent.py
Browse files
agent.py
CHANGED
|
@@ -18,8 +18,9 @@ from langchain_groq import ChatGroq
|
|
| 18 |
# It's recommended to set API keys as environment variables for security.
|
| 19 |
# Fallback to getpass if not set, for interactive environments.
|
| 20 |
def _set_env(var: str):
|
|
|
|
| 21 |
if not os.environ.get(var):
|
| 22 |
-
|
| 23 |
|
| 24 |
|
| 25 |
# Ensure API keys are set from environment variables in the HF Space
|
|
@@ -49,17 +50,68 @@ def python_repl_tool(code: str) -> str:
|
|
| 49 |
- Ensure the code is passed as a single string.
|
| 50 |
"""
|
| 51 |
try:
|
| 52 |
-
#
|
| 53 |
-
|
| 54 |
-
|
|
|
|
|
|
|
| 55 |
result = python_repl.run(code)
|
| 56 |
return f"Execution successful. Result:\n{result}"
|
| 57 |
except Exception as e:
|
| 58 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 ---
|
|
@@ -82,7 +134,8 @@ 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 |
-
|
|
|
|
| 86 |
|
| 87 |
|
| 88 |
def call_tool(state: AgentState):
|
|
@@ -95,7 +148,6 @@ def call_tool(state: AgentState):
|
|
| 95 |
|
| 96 |
for tool_call in last_message.tool_calls:
|
| 97 |
tool_name = tool_call["name"]
|
| 98 |
-
# Find the corresponding tool from the list
|
| 99 |
tool_to_call = next((t for t in tools if t.name == tool_name), None)
|
| 100 |
if not tool_to_call:
|
| 101 |
output = f"Error: Tool '{tool_name}' not found."
|
|
@@ -109,7 +161,8 @@ def call_tool(state: AgentState):
|
|
| 109 |
name=tool_name
|
| 110 |
)
|
| 111 |
)
|
| 112 |
-
|
|
|
|
| 113 |
|
| 114 |
|
| 115 |
def should_continue(state: AgentState):
|
|
|
|
| 18 |
# It's recommended to set API keys as environment variables for security.
|
| 19 |
# Fallback to getpass if not set, for interactive environments.
|
| 20 |
def _set_env(var: str):
|
| 21 |
+
"""Checks for an environment variable and raises an error if not found."""
|
| 22 |
if not os.environ.get(var):
|
| 23 |
+
raise ValueError(f"Error: Environment variable '{var}' is not set. Please configure it in the Space secrets.")
|
| 24 |
|
| 25 |
|
| 26 |
# Ensure API keys are set from environment variables in the HF Space
|
|
|
|
| 50 |
- Ensure the code is passed as a single string.
|
| 51 |
"""
|
| 52 |
try:
|
| 53 |
+
# Use regex to robustly extract code from markdown blocks
|
| 54 |
+
code_match = re.search(r"```(?:python\n)?(.*?)```", code, re.DOTALL)
|
| 55 |
+
if code_match:
|
| 56 |
+
code = code_match.group(1).strip()
|
| 57 |
+
|
| 58 |
result = python_repl.run(code)
|
| 59 |
return f"Execution successful. Result:\n{result}"
|
| 60 |
except Exception as e:
|
| 61 |
+
# Provide a more informative error message
|
| 62 |
+
return f"Error during execution: {e}. Ensure the code is valid Python and does not have syntax errors."
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
# Create a dedicated and secure workspace for file operations
|
| 66 |
+
WORKSPACE_DIR = os.path.join(os.getcwd(), "workspace")
|
| 67 |
+
os.makedirs(WORKSPACE_DIR, exist_ok=True)
|
| 68 |
+
|
| 69 |
+
def _resolve_path(file_name: str) -> str:
|
| 70 |
+
"""Resolves a file path to ensure it's within the secure workspace."""
|
| 71 |
+
# Normalize the path to prevent traversal attacks (e.g., using '..')
|
| 72 |
+
absolute_path = os.path.abspath(os.path.join(WORKSPACE_DIR, file_name))
|
| 73 |
+
if not absolute_path.startswith(WORKSPACE_DIR):
|
| 74 |
+
raisePermissionError("Error: Access denied. Path is outside the designated workspace.")
|
| 75 |
+
return absolute_path
|
| 76 |
+
|
| 77 |
+
@tool
|
| 78 |
+
def read_file(file_name: str) -> str:
|
| 79 |
+
"""Reads the contents of a specified file from the workspace."""
|
| 80 |
+
try:
|
| 81 |
+
safe_path = _resolve_path(file_name)
|
| 82 |
+
with open(safe_path, "r", encoding="utf-8") as f:
|
| 83 |
+
return f.read()
|
| 84 |
+
except FileNotFoundError:
|
| 85 |
+
return f"Error: File '{file_name}' not found in the workspace."
|
| 86 |
+
except Exception as e:
|
| 87 |
+
return f"An error occurred while reading the file: {e}"
|
| 88 |
|
| 89 |
+
@tool
|
| 90 |
+
def write_file(file_name: str, content: str) -> str:
|
| 91 |
+
"""Writes the given content to a specified file in the workspace."""
|
| 92 |
+
try:
|
| 93 |
+
safe_path = _resolve_path(file_name)
|
| 94 |
+
with open(safe_path, "w", encoding="utf-8") as f:
|
| 95 |
+
f.write(content)
|
| 96 |
+
return f"Successfully wrote to {file_name} in the workspace."
|
| 97 |
+
except Exception as e:
|
| 98 |
+
return f"An error occurred while writing to the file: {e}"
|
| 99 |
+
|
| 100 |
+
@tool
|
| 101 |
+
def list_files(directory: str = '.') -> str:
|
| 102 |
+
"""Lists all files and directories in the workspace."""
|
| 103 |
+
try:
|
| 104 |
+
# Ensure listing is confined to the workspace
|
| 105 |
+
safe_dir = _resolve_path(directory)
|
| 106 |
+
files = os.listdir(safe_dir)
|
| 107 |
+
return f"Files in '{directory}':\n" + "\n".join(files)
|
| 108 |
+
except FileNotFoundError:
|
| 109 |
+
return f"Error: Directory '{directory}' not found in the workspace."
|
| 110 |
+
except Exception as e:
|
| 111 |
+
return f"An error occurred: {e}"
|
| 112 |
|
| 113 |
# Aggregate all tools into a list for the agent.
|
| 114 |
+
tools = [web_search_tool, python_repl_tool, read_file, write_file, list_files]
|
| 115 |
|
| 116 |
|
| 117 |
# --- Agent State Definition ---
|
|
|
|
| 134 |
"""Node that invokes the LLM with the current state."""
|
| 135 |
messages = state['messages']
|
| 136 |
response = llm_with_tools.invoke(messages)
|
| 137 |
+
# Append the new response to the history
|
| 138 |
+
return {"messages": messages + [response]}
|
| 139 |
|
| 140 |
|
| 141 |
def call_tool(state: AgentState):
|
|
|
|
| 148 |
|
| 149 |
for tool_call in last_message.tool_calls:
|
| 150 |
tool_name = tool_call["name"]
|
|
|
|
| 151 |
tool_to_call = next((t for t in tools if t.name == tool_name), None)
|
| 152 |
if not tool_to_call:
|
| 153 |
output = f"Error: Tool '{tool_name}' not found."
|
|
|
|
| 161 |
name=tool_name
|
| 162 |
)
|
| 163 |
)
|
| 164 |
+
# Append the tool outputs to the history
|
| 165 |
+
return {"messages": state['messages'] + tool_outputs}
|
| 166 |
|
| 167 |
|
| 168 |
def should_continue(state: AgentState):
|