Dynamically patch a Python function’s source code at runtime

🌙 Eric J Ma’s Website written by Eric J. Ma on 2025-08-23 | tags: python runtime llm security namespace compilation execution functions toolbot monkeypatching In this blog post, I share how I discovered a powerful Python trick: dynamically changing a function’s source code at runtime using the compile and exec functions. This technique enabled me to build more flexible AI bots, like ToolBot, that can generate and execute code with access to the current environment. While this opens up exciting possibilities for LLM-powered agents and generative UIs, it also raises serious security concerns. Curious how this hack can supercharge your AI projects—and what risks you should watch out for? So today, I learned a very dangerous…