Start learning free

LESSON 94 OF 129 · AI ENGINEERING: BUILD YOUR OWN CODING AGENT

Let It Edit a File in Python

Practice

Your agent can read the project. Now it gets a tool that writes: write_file creates a file, or replaces the whole text of a file that exists. Reading can't break anything. Writing can: the model chooses the path, and your code opens whatever it is given.

A path can leave the project in two ways. Two dots mean one folder up, and a path that starts with / starts at the top of the disk:

notes/todo.txt     inside the project
../todo.txt        one folder up: outside
/tmp/todo.txt      the top of the disk: outside

So the tool checks the path itself, in code. A model can be wrong, and a text it reads can talk it into anything. An if in your tool works the same way every time. A refused write returns a text that starts with Error:, so the model learns why and can try again.

In this lesson the model first asks to save its notes as ../NOTES.md. Your program must refuse that, and then write the file the model asks for next:

Model: I'll read cart.py first.
Tool: read_file {'path': 'cart.py'}
Model: Now I'll save the notes one folder up, next to the project.
Tool: write_file {'path': '../NOTES.md', 'text': '# Notes…
Refused: ../NOTES.md
Model: That path is outside the project. I'll save the file inside it.
Tool: write_file {'path': 'NOTES.md', 'text': '# Notes…
Wrote: NOTES.md
Answer: Done: NOTES.md is in the project and says what cart.py does.
Model calls: 4
is_error of the tool results sent: False, True, False
NOTES.md inside workspace/: yes
NOTES.md outside workspace/: no

Then the lesson's check asks your tool for three more paths. ../hack.txt and /tmp/hack.txt must be refused with Error: … is outside the project. Write only to paths inside it. and never written. todo.txt must be written inside workspace, with the result Wrote todo.txt.

Your task: the description write_file_tool is already there. Write the function write_file, offer the tool to the model, and then add the check that refuses a path with .. in it or a / at the start.


Assignment
Follow the Coding Tutorial to build the write_file tool and the check that keeps it inside the project.


Hint
The check sits above the line that opens the file: a return there means nothing is written. The refused result must start with Error:, because that is how run_tools sets is_error.


STEP 1 OF 11
    Ctrl + Enter to check

    Ai Agent Write File in Python

    Keep going with Python1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free