Now that we have a function that can get the contents of a directory, we need one that can get the contents of a file. Again, we'll just return the file contents as a string, or an error string if something went wrong.
As always, we'll safely scope the function to a specific working directory.
def get_file_content(working_directory, file_path):
f'Error: Cannot read "{file_path}" as it is outside the permitted working directory'
f'Error: File not found or is not a regular file: "{file_path}"'
Tips section below.10000 characters, truncate it to 10000, and append this message to the end [...File "{file_path}" truncated at 10000 characters].10000 character limit, I stored it in a config.py file.We don't want to accidentally read a gigantic file and send all that data to the LLM... that's a good way to burn through our token limits.
get_file_content("calculator", "main.py")get_file_content("calculator", "pkg/calculator.py")get_file_content("calculator", "/bin/cat") (this should return an error string)get_file_content("calculator", "pkg/does_not_exist.py") (this should return an error string)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).startswith: Check if a string starts with a specific substringos.path.isfile: Check if a path is a fileExample of reading up to a certain number of characters from a text file:
MAX_CHARS = 10000
with open(file_path, "r") as f:
file_content_string = f.read(MAX_CHARS)