llms-py 3.0.12__py3-none-any.whl → 3.0.14__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,303 @@
1
+ from collections import defaultdict
2
+ from pathlib import Path
3
+ from typing import Annotated, Any, Literal, get_args
4
+
5
+ from .base import BaseTool, CLIResult, ToolError, ToolResult
6
+ from .run import maybe_truncate, run
7
+
8
+ Command_20250124 = Literal[
9
+ "view",
10
+ "create",
11
+ "str_replace",
12
+ "insert",
13
+ "undo_edit",
14
+ ]
15
+
16
+ Command_20250728 = Literal[
17
+ "view",
18
+ "create",
19
+ "str_replace",
20
+ "insert",
21
+ ]
22
+ SNIPPET_LINES: int = 4
23
+
24
+
25
+ class EditTool20250124(BaseTool):
26
+ """
27
+ An filesystem editor tool that allows the agent to view, create, and edit files.
28
+ The tool parameters are defined by Anthropic and are not editable.
29
+ """
30
+
31
+ api_type: Literal["text_editor_20250124"] = "text_editor_20250124"
32
+ name: Literal["str_replace_editor"] = "str_replace_editor"
33
+
34
+ _file_history: dict[Path, list[str]]
35
+
36
+ def __init__(self):
37
+ self._file_history = defaultdict(list)
38
+ super().__init__()
39
+
40
+ def to_params(self) -> Any:
41
+ return {
42
+ "name": self.name,
43
+ "type": self.api_type,
44
+ }
45
+
46
+ async def __call__(
47
+ self,
48
+ *,
49
+ command: Command_20250124,
50
+ path: str,
51
+ file_text: str | None = None,
52
+ view_range: list[int] | None = None,
53
+ old_str: str | None = None,
54
+ new_str: str | None = None,
55
+ insert_line: int | None = None,
56
+ **kwargs,
57
+ ):
58
+ _path = Path(path)
59
+ self.validate_path(command, _path)
60
+ if command == "view":
61
+ return await self.view(_path, view_range)
62
+ elif command == "create":
63
+ if file_text is None:
64
+ raise ToolError("Parameter `file_text` is required for command: create")
65
+ self.write_file(_path, file_text)
66
+ self._file_history[_path].append(file_text)
67
+ return ToolResult(output=f"File created successfully at: {_path}")
68
+ elif command == "str_replace":
69
+ if old_str is None:
70
+ raise ToolError("Parameter `old_str` is required for command: str_replace")
71
+ return self.str_replace(_path, old_str, new_str)
72
+ elif command == "insert":
73
+ if insert_line is None:
74
+ raise ToolError("Parameter `insert_line` is required for command: insert")
75
+ if new_str is None:
76
+ raise ToolError("Parameter `new_str` is required for command: insert")
77
+ return self.insert(_path, insert_line, new_str)
78
+ elif command == "undo_edit":
79
+ return self.undo_edit(_path)
80
+ raise ToolError(
81
+ f"Unrecognized command {command}. The allowed commands for the {self.name} tool are: {', '.join(get_args(Command_20250124))}"
82
+ )
83
+
84
+ def validate_path(self, command: str, path: Path):
85
+ """
86
+ Check that the path/command combination is valid.
87
+ """
88
+ # Check if its an absolute path
89
+ if not path.is_absolute():
90
+ suggested_path = Path("") / path
91
+ raise ToolError(
92
+ f"The path {path} is not an absolute path, it should start with `/`. Maybe you meant {suggested_path}?"
93
+ )
94
+ # Check if path exists
95
+ if not path.exists() and command != "create":
96
+ raise ToolError(f"The path {path} does not exist. Please provide a valid path.")
97
+ if path.exists() and command == "create":
98
+ raise ToolError(f"File already exists at: {path}. Cannot overwrite files using command `create`.")
99
+ # Check if the path points to a directory
100
+ if path.is_dir():
101
+ if command != "view":
102
+ raise ToolError(
103
+ f"The path {path} is a directory and only the `view` command can be used on directories"
104
+ )
105
+
106
+ async def view(self, path: Path, view_range: list[int] | None = None):
107
+ """Implement the view command"""
108
+ if path.is_dir():
109
+ if view_range:
110
+ raise ToolError("The `view_range` parameter is not allowed when `path` points to a directory.")
111
+
112
+ _, stdout, stderr = await run(rf"find {path} -maxdepth 2 -not -path '*/\.*'")
113
+ if not stderr:
114
+ stdout = f"Here's the files and directories up to 2 levels deep in {path}, excluding hidden items:\n{stdout}\n"
115
+ return CLIResult(output=stdout, error=stderr)
116
+
117
+ file_content = self.read_file(path)
118
+ init_line = 1
119
+ if view_range:
120
+ if len(view_range) != 2 or not all(isinstance(i, int) for i in view_range):
121
+ raise ToolError("Invalid `view_range`. It should be a list of two integers.")
122
+ file_lines = file_content.split("\n")
123
+ n_lines_file = len(file_lines)
124
+ init_line, final_line = view_range
125
+ if init_line < 1 or init_line > n_lines_file:
126
+ raise ToolError(
127
+ f"Invalid `view_range`: {view_range}. Its first element `{init_line}` should be within the range of lines of the file: {[1, n_lines_file]}"
128
+ )
129
+ if final_line > n_lines_file:
130
+ raise ToolError(
131
+ f"Invalid `view_range`: {view_range}. Its second element `{final_line}` should be smaller than the number of lines in the file: `{n_lines_file}`"
132
+ )
133
+ if final_line != -1 and final_line < init_line:
134
+ raise ToolError(
135
+ f"Invalid `view_range`: {view_range}. Its second element `{final_line}` should be larger or equal than its first `{init_line}`"
136
+ )
137
+
138
+ if final_line == -1:
139
+ file_content = "\n".join(file_lines[init_line - 1 :])
140
+ else:
141
+ file_content = "\n".join(file_lines[init_line - 1 : final_line])
142
+
143
+ return CLIResult(output=self._make_output(file_content, str(path), init_line=init_line))
144
+
145
+ def str_replace(self, path: Path, old_str: str, new_str: str | None):
146
+ """Implement the str_replace command, which replaces old_str with new_str in the file content"""
147
+ # Read the file content
148
+ file_content = self.read_file(path).expandtabs()
149
+ old_str = old_str.expandtabs()
150
+ new_str = new_str.expandtabs() if new_str is not None else ""
151
+
152
+ # Check if old_str is unique in the file
153
+ occurrences = file_content.count(old_str)
154
+ if occurrences == 0:
155
+ raise ToolError(f"No replacement was performed, old_str `{old_str}` did not appear verbatim in {path}.")
156
+ elif occurrences > 1:
157
+ file_content_lines = file_content.split("\n")
158
+ lines = [idx + 1 for idx, line in enumerate(file_content_lines) if old_str in line]
159
+ raise ToolError(
160
+ f"No replacement was performed. Multiple occurrences of old_str `{old_str}` in lines {lines}. Please ensure it is unique"
161
+ )
162
+
163
+ # Replace old_str with new_str
164
+ new_file_content = file_content.replace(old_str, new_str)
165
+
166
+ # Write the new content to the file
167
+ self.write_file(path, new_file_content)
168
+
169
+ # Save the content to history
170
+ self._file_history[path].append(file_content)
171
+
172
+ # Create a snippet of the edited section
173
+ replacement_line = file_content.split(old_str)[0].count("\n")
174
+ start_line = max(0, replacement_line - SNIPPET_LINES)
175
+ end_line = replacement_line + SNIPPET_LINES + new_str.count("\n")
176
+ snippet = "\n".join(new_file_content.split("\n")[start_line : end_line + 1])
177
+
178
+ # Prepare the success message
179
+ success_msg = f"The file {path} has been edited. "
180
+ success_msg += self._make_output(snippet, f"a snippet of {path}", start_line + 1)
181
+ success_msg += "Review the changes and make sure they are as expected. Edit the file again if necessary."
182
+
183
+ return CLIResult(output=success_msg)
184
+
185
+ def insert(self, path: Path, insert_line: int, new_str: str):
186
+ """Implement the insert command, which inserts new_str at the specified line in the file content."""
187
+ file_text = self.read_file(path).expandtabs()
188
+ new_str = new_str.expandtabs()
189
+ file_text_lines = file_text.split("\n")
190
+ n_lines_file = len(file_text_lines)
191
+
192
+ if insert_line < 0 or insert_line > n_lines_file:
193
+ raise ToolError(
194
+ f"Invalid `insert_line` parameter: {insert_line}. It should be within the range of lines of the file: {[0, n_lines_file]}"
195
+ )
196
+
197
+ new_str_lines = new_str.split("\n")
198
+ new_file_text_lines = file_text_lines[:insert_line] + new_str_lines + file_text_lines[insert_line:]
199
+ snippet_lines = (
200
+ file_text_lines[max(0, insert_line - SNIPPET_LINES) : insert_line]
201
+ + new_str_lines
202
+ + file_text_lines[insert_line : insert_line + SNIPPET_LINES]
203
+ )
204
+
205
+ new_file_text = "\n".join(new_file_text_lines)
206
+ snippet = "\n".join(snippet_lines)
207
+
208
+ self.write_file(path, new_file_text)
209
+ self._file_history[path].append(file_text)
210
+
211
+ success_msg = f"The file {path} has been edited. "
212
+ success_msg += self._make_output(
213
+ snippet,
214
+ "a snippet of the edited file",
215
+ max(1, insert_line - SNIPPET_LINES + 1),
216
+ )
217
+ success_msg += "Review the changes and make sure they are as expected (correct indentation, no duplicate lines, etc). Edit the file again if necessary."
218
+ return CLIResult(output=success_msg)
219
+
220
+ def undo_edit(self, path: Path):
221
+ """Implement the undo_edit command."""
222
+ if not self._file_history[path]:
223
+ raise ToolError(f"No edit history found for {path}.")
224
+
225
+ old_text = self._file_history[path].pop()
226
+ self.write_file(path, old_text)
227
+
228
+ return CLIResult(output=f"Last edit to {path} undone successfully. {self._make_output(old_text, str(path))}")
229
+
230
+ def read_file(self, path: Path):
231
+ """Read the content of a file from a given path; raise a ToolError if an error occurs."""
232
+ try:
233
+ return path.read_text()
234
+ except Exception as e:
235
+ raise ToolError(f"Ran into {e} while trying to read {path}") from None
236
+
237
+ def write_file(self, path: Path, file: str):
238
+ """Write the content of a file to a given path; raise a ToolError if an error occurs."""
239
+ try:
240
+ path.write_text(file)
241
+ except Exception as e:
242
+ raise ToolError(f"Ran into {e} while trying to write to {path}") from None
243
+
244
+ def _make_output(
245
+ self,
246
+ file_content: str,
247
+ file_descriptor: str,
248
+ init_line: int = 1,
249
+ expand_tabs: bool = True,
250
+ ):
251
+ """Generate output for the CLI based on the content of a file."""
252
+ file_content = maybe_truncate(file_content)
253
+ if expand_tabs:
254
+ file_content = file_content.expandtabs()
255
+ file_content = "\n".join([f"{i + init_line:6}\t{line}" for i, line in enumerate(file_content.split("\n"))])
256
+ return f"Here's the result of running `cat -n` on {file_descriptor}:\n" + file_content + "\n"
257
+
258
+
259
+ class EditTool20250728(EditTool20250124):
260
+ api_type: Literal["text_editor_20250728"] = "text_editor_20250728" # pyright: ignore[reportIncompatibleVariableOverride]
261
+ name: Literal["str_replace_based_edit_tool"] = "str_replace_based_edit_tool" # pyright: ignore[reportIncompatibleVariableOverride]
262
+
263
+
264
+ class EditTool20241022(EditTool20250124):
265
+ api_type: Literal["text_editor_20250429"] = "text_editor_20250429" # pyright: ignore[reportIncompatibleVariableOverride]
266
+
267
+
268
+ g_tool = None
269
+
270
+
271
+ async def edit(
272
+ command: Command_20250124,
273
+ path: Annotated[str, "The absolute path to the file or directory"],
274
+ file_text: Annotated[str | None, "The content to write to the file (required for create)"] = None,
275
+ view_range: Annotated[list[int] | None, "The range of lines to view (e.g. [1, 10])"] = None,
276
+ old_str: Annotated[str | None, "The string to replace (required for str_replace)"] = None,
277
+ new_str: Annotated[str | None, "The replacement string (required for str_replace and insert)"] = None,
278
+ insert_line: Annotated[int | None, "The line number after which to insert (required for insert)"] = None,
279
+ ) -> list[dict[str, Any]]:
280
+ """
281
+ An filesystem editor tool that allows the agent to view, create, and edit files.
282
+ """
283
+ global g_tool
284
+ if g_tool is None:
285
+ g_tool = EditTool20250124()
286
+
287
+ view_range_values = None
288
+ if view_range:
289
+ view_range_values = [int(x) for x in view_range]
290
+
291
+ result = await g_tool(
292
+ command,
293
+ path if path else None,
294
+ file_text if file_text else None,
295
+ view_range_values,
296
+ old_str if old_str else None,
297
+ new_str if new_str else None,
298
+ int(insert_line) if insert_line else None,
299
+ )
300
+ if isinstance(result, Exception):
301
+ raise result
302
+ else:
303
+ return result.to_tool_results()