View directory or file contents with optional line range and numbers
Exported source
def view(path:str, view_range:tuple[int,int]=None, nums:bool=False):'View directory or file contents with optional line range and numbers'try: p = Path(path).expanduser().resolve()ifnot p.exists(): returnf'Error: File not found: {p}'if p.is_dir(): res = [str(f) for f in p.glob('**/*') ifnotany(part.startswith('.') for part in f.relative_to(p).parts)]returnf'Directory contents of {p}:\n'+'\n'.join(res) lines = p.read_text().splitlines() s,e =1,len(lines)if view_range: s,e = view_rangeifnot (1<= s <=len(lines)): returnf'Error: Invalid start line {s}'if e !=-1andnot (s <= e <=len(lines)): returnf'Error: Invalid end line {e}' lines = lines[s-1:Noneif e==-1else e]return'\n'.join([f'{i+s-1:6d} │ {l}'for i,l inenumerate(lines,1)] if nums else lines)exceptExceptionas e: returnf'Error viewing file: {str(e)}'
Creates a new file with the given content at the specified path
Exported source
def create(path: str, file_text: str, overwrite:bool=False) ->str:'Creates a new file with the given content at the specified path'try: p = Path(path)if p.exists():ifnot overwrite: returnf'Error: File already exists: {p}' p.parent.mkdir(parents=True, exist_ok=True) p.write_text(file_text)returnf'Created file {p} containing:\n{file_text}'exceptExceptionas e: returnf'Error creating file: {str(e)}'
def insert(path: str, insert_line: int, new_str: str) ->str:'Insert new_str at specified line number'try: p = Path(path)ifnot p.exists(): returnf'Error: File not found: {p}' content = p.read_text().splitlines()ifnot (0<= insert_line <=len(content)): returnf'Error: Invalid line number {insert_line}' content.insert(insert_line, new_str) new_content ='\n'.join(content) p.write_text(new_content)returnf'Inserted text at line {insert_line} in {p}.\nNew contents:\n{new_content}'exceptExceptionas e: returnf'Error inserting text: {str(e)}'
insert('test.txt', 0, 'Let\'s add a new line')print(view('test.txt', nums=True))
Replace first occurrence of old_str with new_str in file
Exported source
def str_replace(path: str, old_str: str, new_str: str) ->str:'Replace first occurrence of old_str with new_str in file'try: p = Path(path)ifnot p.exists(): returnf'Error: File not found: {p}' content = p.read_text() count = content.count(old_str)if count ==0: return'Error: Text not found in file'if count >1: returnf'Error: Multiple matches found ({count})' new_content = content.replace(old_str, new_str, 1) p.write_text(new_content)returnf'Replaced text in {p}.\nNew contents:\n{new_content}'exceptExceptionas e: returnf'Error replacing text: {str(e)}'
Dispatcher for Anthropic Text Editor tool commands: view, str_replace, create, insert, undo_edit.
model = models[1]
c = Chat(model, tools=[text_editor_conf['sonnet']], ns=mk_ns(str_replace_based_edit_tool))# c.toolloop('Please explain what my _quarto.yml does. Use your tools')