/ src / python / txtai / agent / tool / bash.py
bash.py
 1  """
 2  Bash imports
 3  """
 4  
 5  import subprocess
 6  
 7  from smolagents import Tool
 8  
 9  
10  class BashTool(Tool):
11      """
12      The BashTool runs a command through a subprocess. This tool only allows a small subset of commands.
13      More can be added through configuration.
14      """
15  
16      # pylint: disable=W0231
17      def __init__(self, allowed=None):
18          """
19          Creates a BashTool.
20  
21          Args:
22              allowed: list of allowed commands to run, has limited set of defaults
23          """
24  
25          # Tool parameters
26          self.name = "bash"
27          self.description = "Implementation of a bash shell subprocess tool. Runs a shell command and returns the output."
28          self.inputs = {
29              "command": {"type": "array", "description": "Command to run. Follows Python subprocess.open pattern for command as a list of arguments."}
30          }
31          self.output_type = "any"
32  
33          # Default list of allowed commands
34          self.allowed = allowed if allowed else ["cat", "cut", "diff", "find", "grep", "head", "ls", "tail"]
35  
36          # Validate parameters and initialize tool
37          super().__init__()
38  
39      # pylint: disable=W0221
40      def forward(self, command):
41          """
42          Runs a shell command as a subprocess.
43  
44          Args:
45              command: command arguments as a list
46  
47          Returns:
48              command output
49          """
50  
51          output = None
52          if command and command[0] in self.allowed:
53              output = subprocess.run(command, capture_output=True, text=True, check=False).stdout
54  
55          return output