CodeSpace runs Python and JavaScript code in a secure, containerized environment through the AgentBay SDK.
Quick start
Run a Python snippet in a CodeSpace session:
import os
from agentbay import AgentBay, CreateSessionParams
agent_bay = AgentBay(api_key=os.environ.get("AGENTBAY_API_KEY"))
session_params = CreateSessionParams(image_id="code_latest")
result = agent_bay.create(session_params)
session = result.session
output = session.code.run_code('print("Hello from CodeSpace!")', "python")
print(output.result)
agent_bay.delete(session)The code above creates a session with the code_latest image, runs one line of Python, and prints the output. All subsequent examples assume a session is already created using the same pattern.
run_code() vs execute_command()
CodeSpace offers two ways to run code:
Method | Purpose | Input | Output field | Best for |
| Interpret code in a sandboxed runtime | Python or JavaScript source code string |
| Self-contained snippets, calculations, and data processing |
| Run a shell command | Shell command string (e.g., |
| Saved scripts, package installation, shell operations, and command-line arguments |
Use run_code() to execute inline code directly. Use execute_command() to run shell commands and scripts from the file system.
Run Python code
Basic execution
Print system information from inside the CodeSpace environment:
code = """
import os
import sys
print(f"Python version: {sys.version}")
print(f"Current directory: {os.getcwd()}")
print("Hello from AgentBay!")
"""
result = session.code.run_code(code, "python")
if result.success:
print("Output:", result.result)
# Output: Python version: 3.11.2 (main, Apr 28 2025, 14:11:48) [GCC 12.2.0]
# Current directory: /workspace
# Hello from AgentBay!
else:
print("Execution failed:", result.error_message)Calculations
Define and call functions, use list comprehensions, and work with the standard library:
code = """
import math
# Calculate factorial
def factorial(n):
return math.factorial(n)
# Fibonacci sequence
def fibonacci(n):
if n <= 1:
return n
return fibonacci(n-1) + fibonacci(n-2)
print(f"Factorial of 10: {factorial(10)}")
print(f"10th Fibonacci number: {fibonacci(10)}")
# List comprehension
squares = [x**2 for x in range(1, 11)]
print(f"Squares: {squares}")
"""
result = session.code.run_code(code, "python")
if result.success:
print("Output:", result.result)
# Output: Factorial of 10: 3628800
# 10th Fibonacci number: 55
# Squares: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]Run JavaScript code
Basic Node.js execution
Pass "javascript" as the language parameter to run Node.js code:
js_code = """
const fs = require('fs');
const path = require('path');
console.log('Node.js version:', process.version);
console.log('Current directory:', process.cwd());
// Create a simple file
fs.writeFileSync('/tmp/hello.txt', 'Hello from Node.js!');
console.log('File created successfully');
"""
result = session.code.run_code(js_code, "javascript")
if result.success:
print("Output:", result.result)
# Output: Node.js version: v18.20.4
# Current directory: /workspace
# File created successfully
else:
print("Execution failed:", result.error_message)Data processing
Work with arrays and objects in JavaScript:
js_code = """
// Array operations
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const sum = numbers.reduce((a, b) => a + b, 0);
const avg = sum / numbers.length;
const squares = numbers.map(x => x * x);
console.log('Numbers:', numbers);
console.log('Sum:', sum);
console.log('Average:', avg);
console.log('Squares:', squares);
// Object operations
const data = {
name: 'AgentBay',
version: '1.0',
features: ['Python', 'JavaScript', 'File I/O']
};
console.log('\\nData:', JSON.stringify(data, null, 2));
"""
result = session.code.run_code(js_code, "javascript")
if result.success:
print("Output:", result.result)
# Output: Numbers: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Sum: 55
# Average: 5.5
# Squares: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
#
# Data: {
# "name": "AgentBay",
# "version": "1.0",
# "features": [
# "Python",
# "JavaScript",
# "File I/O"
# ]
# }Combine code execution with file I/O
Read and write files through session.file_system, then combine file operations with code execution to build multi-step workflows.
Write and run a script
Write a Python script to the file system, run it with execute_command(), and read the output file:
script_content = """
import json
import sys
data = {
'message': 'Hello from uploaded script',
'args': sys.argv[1:] if len(sys.argv) > 1 else []
}
with open('/tmp/output.json', 'w') as f:
json.dump(data, f, indent=2)
print(json.dumps(data, indent=2))
"""
# Write the script
write_result = session.file_system.write_file("/tmp/script.py", script_content)
# Run the script with arguments
exec_result = session.command.execute_command("python3 /tmp/script.py arg1 arg2")
if exec_result.success:
print("Script output:", exec_result.output)
# Script output: {
# "message": "Hello from uploaded script",
# "args": [
# "arg1",
# "arg2"
# ]
# }
# Read the generated output file
output_result = session.file_system.read_file("/tmp/output.json")
if output_result.success:
print("Output file content:", output_result.content)Multi-file projects
Create a directory structure, write multiple source files, and run the project:
# Create the project directory
session.file_system.create_directory("/workspace/myproject")
main_py = """
from utils import greet
if __name__ == "__main__":
print(greet("AgentBay"))
"""
utils_py = """
def greet(name):
return f"Hello, {name}!"
"""
# Write source files
session.file_system.write_file("/workspace/myproject/main.py", main_py)
session.file_system.write_file("/workspace/myproject/utils.py", utils_py)
# Run the project
result = session.command.execute_command("cd /workspace/myproject && python3 main.py")
if result.success:
print("Project output:", result.output)
# Project output: Hello, AgentBay!Timeout behavior
The run_code() method has a default timeout of 60 seconds.
Because of gateway limitations, each request cannot exceed 60 seconds.
# The default timeout is 60 seconds
result = session.code.run_code(code, "python")
# Specify a custom timeout of up to 60 seconds
result = session.code.run_code(code, "python", timeout_s=60)The 60-second limit applies per request. Break long-running workloads into smaller steps that each complete within this window.
Supported standard libraries
CodeSpace comes pre-installed with standard libraries for Python and Node.js. For optimal performance and reliability, use only built-in modules, such as the following:
Language | Available standard modules |
Python (3.11.2) |
|
Node.js (v18.20.4) |
|
Clean up sessions
Delete the session when finished to release resources:
agent_bay.delete(session)In production code, wrap the session lifecycle in a try/finally block to handle errors gracefully:
import os
from agentbay import AgentBay, CreateSessionParams
agent_bay = AgentBay(api_key=os.environ.get("AGENTBAY_API_KEY"))
session_params = CreateSessionParams(image_id="code_latest")
result = agent_bay.create(session_params)
session = result.session
try:
output = session.code.run_code('print("Hello!")', "python")
print(output.result)
finally:
agent_bay.delete(session)