

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Still calibrating
click for more info
Not enough gems
Cost: 6 gems
1: Calculator App
incomplete
2: Validate Paths
incomplete
3: List Files
incomplete
4: Get File Content
incomplete
5: Write Files
incomplete
6: Run Python
incomplete
This lesson's interactive features are locked, please to keep using them
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.
def write_file(working_directory: str, file_path: str, content: str) -> str:
f'Error: Cannot write to "{file_path}" as it is outside the permitted working directory'
f'Error: Cannot write to "{file_path}" as it is a directory'
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.
os.path.abspath(): Get an absolute path from a relative pathos.path.join(): Join two paths together safely (handles slashes)os.path.normpath(): Normalize a path (handles things like ..)os.path.commonpath(): Get the common sub-path shared by multiple pathsos.path.isdir(): Check if a path points to an existing directoryos.makedirs(): Create a directory, along with any necessary parent directories (note the optional exist_ok argument)os.path.dirname(): Get the parent directory of a given pathopen(): Open a file for reading or writing.write(): Write a string to a text fileExample of writing to a file:
with open(file_path, "w") as f:
f.write(content)