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

Run Python

If you thought allowing an LLM to write files was a bad idea...

You ain't seen nothin' yet! (Praise the basilisk.)

It's time to build the functionality for our agent to run arbitrary Python code.

Now, it's worth pausing to point out the inherent security risks here. We have a few things going for us:

  1. We'll only allow the LLM to run code in a specific directory (the working_directory).
  2. We'll use a 30-second timeout to prevent it from running indefinitely.

But aside from that... yes, the LLM can run arbitrary code that we place (or it places) in the working directory... so be careful. As long as you use this AI agent only for the simple tasks we're doing in this course, you should be fine.

Do not give this program to others for them to use! It doesn't have all the security and safety features that a production AI agent would have. This is for learning purposes only.

Assignment

  1. def run_python_file(
        working_directory: str, file_path: str, args: list[str] | None = None
    ) -> str:
    
  2. f'Error: Cannot execute "{file_path}" as it is outside the permitted working directory'
    
  3. f'Error: "{file_path}" does not exist or is not a regular file'
    
  4. f'Error: "{file_path}" is not a Python file'
    
  5. command = ["python", absolute_file_path]
    
  6. f"Error: executing Python file: {e}"
    

Run and submit the CLI tests.