Refactor agent.py