/ src / python / txtai / agent / tool / edit.py
edit.py
 1  """
 2  Edit imports
 3  """
 4  
 5  import difflib
 6  
 7  from smolagents import Tool
 8  
 9  
10  class EditTool(Tool):
11      """
12      The EditTool modifies content in a file.
13      """
14  
15      # pylint: disable=W0231
16      def __init__(self):
17          """
18          Creates an EditTool.
19          """
20  
21          # Tool parameters
22          self.name = "edit"
23          self.description = "Implementation of a file edit tool. Makes in-place edits to content in a file."
24          self.inputs = {
25              "path": {"type": "string", "description": "Path of file to edit"},
26              "search": {"type": "string", "description": "String to replace"},
27              "replace": {"type": "string", "description": "Replacement string"},
28          }
29          self.output_type = "any"
30  
31          # Validate parameters and initialize tool
32          super().__init__()
33  
34      # pylint: disable=W0221
35      def forward(self, path, search, replace):
36          """
37          Modifies content in a file. Returns a diff of the changes, if any.
38  
39          Args:
40              path: file to edit
41              search: string to replace
42              replace: replacement
43  
44          Returns:
45              diff
46          """
47  
48          content = None
49          with open(path, "r", encoding="utf-8") as f:
50              content = f.read()
51  
52          # Make edits
53          modified = content.replace(search, replace)
54          if modified != content:
55              with open(path, "w", encoding="utf-8") as f:
56                  f.write(modified)
57  
58          # Return diff of file edits
59          return "".join(difflib.unified_diff(content.splitlines(True), modified.splitlines(True), path, path))