Spaces:
Sleeping
Sleeping
File size: 1,928 Bytes
ae04b8f |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
from typing import Any, Optional
from smolagents.tools import Tool
import duckduckgo_search
import subprocess
import sys
class ShellCommandTool(Tool):
name = "shell_command"
description = "Executes a shell command and returns the result."
inputs = {'command': {'type': 'string', 'description': 'The shell command to execute.'}}
output_type = "string"
def __init__(self, timeout=60, **kwargs):
super().__init__()
self.timeout = timeout
# Detect the operating system
self.is_windows = sys.platform.startswith('win')
def forward(self, command: str) -> str:
try:
# Use shell=True for complex commands
# Use different configurations based on the OS
if self.is_windows:
process = subprocess.run(
command,
capture_output=True,
text=True,
shell=True,
timeout=self.timeout,
executable="cmd.exe" if self.is_windows else None
)
else:
process = subprocess.run(
command,
capture_output=True,
text=True,
shell=True,
timeout=self.timeout
)
# Return stdout and stderr if present
result = ""
if process.stdout:
result += f"## Standard Output\n```\n{process.stdout}\n```\n\n"
if process.stderr:
result += f"## Standard Error\n```\n{process.stderr}\n```\n\n"
result += f"Exit Code: {process.returncode}"
return result
except subprocess.TimeoutExpired:
return "The command has timed out."
except Exception as e:
return f"Error while executing the command: {str(e)}"
|