We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

Write Files

Up until now, our program has been read-only... now it's getting really dangerous fun! We'll give our agent the ability to write and overwrite files, within strict limits.

Assignment

  1. def write_file(working_directory: str, file_path: str, content: str) -> str:
    
  2. f'Error: Cannot write to "{file_path}" as it is outside the permitted working directory'
    
  3. f'Error: Cannot write to "{file_path}" as it is a directory'
    
  4. f'Successfully wrote to "{file_path}" ({len(content)} characters written)'
    

    It's important to return a success string so that our LLM knows that the action it took actually worked. Feedback loops, feedback loops, feedback loops!

    • write_file("calculator", "lorem.txt", "wait, this isn't lorem ipsum")
    • write_file("calculator", "pkg/morelorem.txt", "lorem ipsum dolor sit amet")
    • write_file("calculator", "/tmp/temp.txt", "this should not be allowed")

Run and submit the CLI tests.

Tips

Example of writing to a file:

with open(file_path, "w") as f:
    f.write(content)