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

Validate Paths

We need to give our agent the ability to do stuff. We'll start by allowing it to list the contents of a directory and see each file's metadata (name and size).

Before we integrate this function with our LLM agent, let's just build the function itself. Now remember, LLMs work with text, so our end goal with this function is for it to accept a directory path and return a string that represents the contents of that directory.

But the first step is the most important: making sure the requested directory is safely inside the working directory that we allow the agent to use.

Assignment

  1. def get_files_info(working_directory: str, directory: str = ".") -> str:
    

    For reference, here's my project structure so far:

    project_root/
    ├── calculator/
    │   ├── main.py
    │   ├── pkg/
    │   │   ├── calculator.py
    │   │   └── render.py
    │   └── tests.py
    └── functions/
        └── get_files_info.py
    

    The key idea is that the directory parameter will be treated as a relative path within the working_directory. We'll allow the LLM agent to specify which directory it wants to scan, but the working_directory will be set by us. This means we can limit the scope of directories and files that the LLM is able to view.

    1. target_dir = os.path.normpath(os.path.join(working_dir_abs, directory))
      
    2. # Will be True or False
      valid_target_dir = os.path.commonpath([working_dir_abs, target_dir]) == working_dir_abs
      
    3. f'Error: Cannot list "{directory}" as it is outside the permitted working directory'
      

    Now our LLM agent has some guardrails: we never want it to be able to perform any work outside the working_directory that we give it.

    Without this restriction, the LLM might run amok anywhere on the machine, reading sensitive files or overwriting important data. This is a very important step that we'll bake into every function the LLM can call.

  2. f'Error: "{directory}" is not a directory'
    

    All of our "tool call" functions, including get_files_info, should always return a string. If errors can be raised inside them, we need to catch those errors and return a string describing the error instead. This will allow the LLM to handle errors gracefully.

  3. f'Success: "{directory}" is within the working directory'
    
  4. To import from a subdirectory, use this syntax: from DIRNAME.FILENAME import FUNCTION_NAME

    Where DIRNAME is the name of the subdirectory, FILENAME is the name of the file without the .py extension, and FUNCTION_NAME is the name of the function you want to import.

Run and submit the CLI tests.

Tips

Here are some standard library functions you'll find helpful: