implemented sessions for AI, reogarnized code