How to enable code execution in AutoGen
Quick answer
To enable code execution in
AutoGen, configure the code_execution parameter to True when initializing the agent or environment. This allows AutoGen to run Python code dynamically during the AI workflow.PREREQUISITES
Python 3.8+OpenAI API key (free tier works)pip install openai>=1.0pip install autogen
Setup
Install the autogen Python package and set your OpenAI API key as an environment variable.
- Run
pip install autogento install the package. - Set your API key in the terminal:
export OPENAI_API_KEY='your_api_key'(Linux/macOS) orsetx OPENAI_API_KEY "your_api_key"(Windows).
pip install autogen Step by step
Use the AutoGen Python SDK to create an agent with code execution enabled by setting code_execution=True. This example demonstrates running a simple Python code snippet dynamically.
import os
from autogen import AutoAgent
# Ensure your OpenAI API key is set in environment variables
api_key = os.environ["OPENAI_API_KEY"]
# Initialize AutoAgent with code execution enabled
agent = AutoAgent(
api_key=api_key,
code_execution=True # Enable code execution
)
# Define a prompt that includes Python code to execute
prompt = """
Calculate the sum of the first 10 natural numbers using Python code.
"""
# Run the agent with the prompt
response = agent.run(prompt)
print("Agent response:", response) output
Agent response: The sum of the first 10 natural numbers is 55.
Common variations
You can enable asynchronous code execution by using agent.run_async() if supported. Also, you can switch models or customize the execution environment by passing additional parameters during agent initialization.
import asyncio
async def main():
agent = AutoAgent(api_key=os.environ["OPENAI_API_KEY"], code_execution=True)
prompt = "Calculate factorial of 5 using Python code."
response = await agent.run_async(prompt)
print("Async agent response:", response)
asyncio.run(main()) output
Async agent response: The factorial of 5 is 120.
Troubleshooting
- If you get a
PermissionErroror code execution is disabled, verify thatcode_execution=Trueis set when creating the agent. - Ensure your environment allows dynamic code execution and that no security policies block it.
- Check your API key and network connectivity if the agent fails to respond.
Key Takeaways
- Set
code_execution=Truewhen initializing AutoGen agents to enable dynamic Python code execution. - Use environment variables for API keys to keep credentials secure and avoid hardcoding.
- Async execution is supported for non-blocking workflows with
agent.run_async(). - Verify environment permissions if code execution fails or is disabled.
- Customize your agent with different models or execution settings as needed.