Whenever it gets in a cycle of fucking up, I ask it to break the code down into smaller functions and write a test suite for each individually.
Tell it what language or packages to use or it might make selections that add dependencies or require installing stuff on your computer.
Tell it how you want your code written or it will be an extra chore to accommodate linting requirements.
Basically just being very explicit.