YepCode Executor: Serverless Code Execution for AG2 Agents#
This notebook demonstrates how to use the YepCode Executor with AG2 agents for secure, scalable serverless code execution. YepCode provides production-grade sandboxes that can run Python and JavaScript code with automatic dependency management.
Key Benefits#
- Serverless Execution: No need to manage infrastructure
- Secure Sandboxes: Code runs in isolated, secure environments
- Automatic Dependencies: NPM and PyPI packages are installed automatically
- Multi-Language Support: Python and JavaScript execution
- Production Ready: Built for enterprise-scale applications
Prerequisites#
-
Install AG2 with YepCode support:
-
Get a YepCode API token from yepcode.io
-
Set your API tokens as environment variables:
import os
from autogen import ConversableAgent, LLMConfig
from autogen.coding import YepCodeCodeExecutor
# Ensure you have your API tokens set
assert os.getenv("YEPCODE_API_TOKEN"), "Please set YEPCODE_API_TOKEN environment variable"
assert os.getenv("OPENAI_API_KEY"), "Please set OPENAI_API_KEY environment variable (or configure another LLM provider)"
Example 1: Basic YepCode Executor Setup#
First, let’s create a basic YepCode executor and test it with a simple code execution task.
# Initialize YepCode executor
yepcode_executor = YepCodeCodeExecutor(
timeout=120, # Timeout in seconds
remove_on_done=False, # Keep execution logs for debugging
sync_execution=True, # Wait for execution to complete
)
# Create an agent with YepCode executor
code_executor_agent = ConversableAgent(
"code_executor_agent",
llm_config=False, # Turn off LLM for this agent
code_execution_config={"executor": yepcode_executor},
human_input_mode="NEVER",
)
print("YepCode executor agent created successfully!")
# Test basic Python execution
task = """
Run this Python code:
```python
import datetime
import math
now = datetime.datetime.now()
print(f"Current time: {now}")
print(f"Square root of 144: {math.sqrt(144)}")
# Return a message
return "Hello from YepCode serverless execution!"
```
"""
reply = code_executor_agent.generate_reply(messages=[{"role": "user", "content": task}])
print(reply)
Example 2: Complete AI Agent with YepCode#
Now let’s create a complete setup with an AI assistant that can write and execute code using YepCode.
# Configure LLM (using OpenAI as example)
llm_config = LLMConfig(
model="gpt-5-nano",
api_key=os.environ["OPENAI_API_KEY"],
)
# Create code writer agent
code_writer_system_message = """
You are a helpful AI assistant that writes and executes code using YepCode's serverless platform.
When writing code:
1. Use Python or JavaScript as appropriate for the task
2. Include all necessary imports and dependencies (they will be installed automatically)
3. Write complete, executable code blocks
4. Return meaningful results using 'return' statements
5. Add informative print/console.log statements to show progress
For data analysis tasks, prefer Python with pandas, numpy, matplotlib, etc.
For web scraping or API calls, you can use either Python (requests, beautifulsoup) or JavaScript (axios, cheerio).
Always wrap your code in appropriate code blocks with language specification.
Reply 'TERMINATE' when the task is completed successfully.
"""
with llm_config:
code_writer_agent = ConversableAgent(
"code_writer_agent",
system_message=code_writer_system_message,
max_consecutive_auto_reply=5,
code_execution_config=False, # This agent writes code but doesn't execute it
)
# Update code executor agent to work with the writer
code_executor_agent = ConversableAgent(
"code_executor_agent",
llm_config=False,
code_execution_config={"executor": yepcode_executor},
human_input_mode="NEVER",
is_termination_msg=lambda x: x.get("content", "").rstrip().endswith("TERMINATE"),
)
print("AI coding team with YepCode executor ready!")
Data Analysis Example#
Let’s ask our AI agent to perform some data analysis using Python libraries.
data_analysis_task = """
Create a dataset of 100 random sales records with the following columns:
- date (random dates from the last 12 months)
- product_category (choose from: Electronics, Clothing, Books, Home, Sports)
- sales_amount (random amounts between $10 and $500)
- region (choose from: North, South, East, West)
Then perform the following analysis:
1. Calculate total sales by category
2. Find the average sales amount by region
3. Identify the top-selling month
4. Create a summary report
Present the results in a clear, formatted output.
"""
chat_result = code_executor_agent.initiate_chat(
code_writer_agent,
message=data_analysis_task,
max_turns=10,
)
print("\n" + "=" * 50)
print("Data Analysis Task Completed!")
print("=" * 50)
API Integration Example#
Now let’s demonstrate fetching and analyzing data from a public API.
api_task = """
Fetch cryptocurrency data from the CoinGecko API and analyze it:
1. Get the current price data for the top 5 cryptocurrencies by market cap
2. Calculate the total market cap of these top 5 coins
3. Find which coins have gained or lost the most in the last 24 hours
4. Create a formatted summary table showing:
- Coin name and symbol
- Current price (USD)
- 24h price change (%)
- Market cap
Use the CoinGecko API: https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&order=market_cap_desc&per_page=5&page=1
"""
chat_result = code_executor_agent.initiate_chat(
code_writer_agent,
message=api_task,
max_turns=10,
)
print("\n" + "=" * 50)
print("Cryptocurrency Analysis Completed!")
print("=" * 50)
Example 3: Using Factory Pattern#
AG2 also supports creating YepCode executors using the factory pattern for more convenient configuration.
from autogen.coding import CodeExecutorFactory
# Create YepCode executor using factory
factory_executor = CodeExecutorFactory.create({
"executor": "yepcode",
"yepcode": {
"timeout": 90,
"remove_on_done": True, # Clean up after execution
"sync_execution": True,
},
})
# Create agent with factory-created executor
factory_agent = ConversableAgent(
"factory_agent",
llm_config=False,
code_execution_config={"executor": factory_executor},
human_input_mode="NEVER",
)
# Test quick calculation
math_task = """
Calculate the following using Python:
```python
import math
# Calculate compound interest
principal = 10000 # Initial investment
rate = 0.07 # 7% annual interest
time = 10 # 10 years
n = 4 # Compounded quarterly
amount = principal * (1 + rate/n)**(n*time)
interest_earned = amount - principal
print(f"Principal: ${principal:,.2f}")
print(f"Final Amount: ${amount:,.2f}")
print(f"Interest Earned: ${interest_earned:,.2f}")
return {
'principal': principal,
'final_amount': round(amount, 2),
'interest_earned': round(interest_earned, 2)
}
```
"""
result = factory_agent.generate_reply(messages=[{"role": "user", "content": math_task}])
print(result)
Summary#
This notebook demonstrated the key features of the YepCode Executor for AG2:
Key Features Covered:#
- Basic Setup: How to create and configure YepCode executors
- Multi-Language Support: Python and JavaScript execution
- AI Agent Integration: Using YepCode with AI agents for code generation and execution
- Automatic Dependencies: NPM and PyPI packages installed automatically
- Factory Pattern: Using the CodeExecutorFactory for convenience
Benefits of YepCode:#
- Serverless: No infrastructure management required
- Secure: Isolated sandbox environments
- Scalable: Production-grade execution platform
- Developer Friendly: Automatic dependency management
- Multi-Language: Python and JavaScript support
- Enterprise Ready: Built for production workloads
Next Steps:#
- Get your YepCode API token at yepcode.io
- Install AG2 with YepCode support:
pip install ag2[yepcode]
- Start building powerful AI agents with serverless code execution!
For more information: - YepCode Documentation - AG2 Documentation - AG2 Code Execution Guide