このトピックでは、Alibaba Cloud AgentBay SDK の CodeSpace 環境におけるコード実行機能について説明します。CodeSpace は、Python および JavaScript コードの実行に最適化された専用の開発環境を提供します。
概要
CodeSpace は AgentBay の開発環境です。以下の特徴があります。
多言語サポート:Python および JavaScript/Node.js のコードを実行できます。
分離された実行:安全なコンテナ化された環境でコードを実行します。
開発ツール:プリインストールされたインタープリターと開発ツール。
ファイル操作:ファイルの読み書きを行い、スクリプトを実行できます。
CodeSpace 環境
CodeSpace セッションの作成
コード実行機能を使用するには、code_latest ランタイムイメージを使用してセッションを作成します。
from agentbay import AgentBay
from agentbay.session_params import CreateSessionParams
agent_bay = AgentBay(api_key="your-api-key")
session_params = CreateSessionParams(image_id="code_latest")
result = agent_bay.create(session_params)
if result.success:
session = result.session
print(f"CodeSpace session created: {session.session_id}")
else:
print(f"Session creation failed: {result.error_message}")Python コードの実行
基本的な Python の実行
from agentbay import AgentBay
from agentbay.session_params import CreateSessionParams
agent_bay = AgentBay(api_key="your-api-key")
session_params = CreateSessionParams(image_id="code_latest")
result = agent_bay.create(session_params)
if result.success:
session = result.session
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)
# 出力: 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)
agent_bay.delete(session)計算を含む Python コード
session_params = CreateSessionParams(image_id="code_latest")
result = agent_bay.create(session_params)
if result.success:
session = result.session
code = """
import math
# 階乗を計算
def factorial(n):
return math.factorial(n)
# フィボナッチ数列
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)}")
# リスト内包表記
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)
# 出力: Factorial of 10: 3628800
# 10th Fibonacci number: 55
# Squares: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
agent_bay.delete(session)
JavaScript コードの実行
Node.js コードの実行
from agentbay import AgentBay
from agentbay.session_params import CreateSessionParams
agent_bay = AgentBay(api_key="your-api-key")
session_params = CreateSessionParams(image_id="code_latest")
result = agent_bay.create(session_params)
if result.success:
session = result.session
js_code = """
const fs = require('fs');
const path = require('path');
console.log('Node.js version:', process.version);
console.log('Current directory:', process.cwd());
// 簡単なファイルを作成
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)
# 出力: Node.js version: v18.20.5
# Current directory: /workspace
# File created successfully
else:
print("Execution failed:", result.error_message)
agent_bay.delete(session)データ処理を含む JavaScript コード
session_params = CreateSessionParams(image_id="code_latest")
result = agent_bay.create(session_params)
if result.success:
session = result.session
js_code = """
// 配列操作
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);
// オブジェクト操作
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)
# 出力: 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"
# ]
# }
agent_bay.delete(session)ファイル I/O を伴うコードの実行
スクリプトの書き込みと実行
from agentbay import AgentBay
agent_bay = AgentBay(api_key="your-api-key")
result = agent_bay.create()
if result.success:
session = result.session
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_result = session.file_system.write_file("/tmp/script.py", script_content)
if write_result.success:
print("Script uploaded successfully")
exec_result = session.command.execute_command("python3 /tmp/script.py arg1 arg2")
if exec_result.success:
print("Script output:", exec_result.output)
# スクリプトの出力: {
# "message": "Hello from uploaded script",
# "args": [
# "arg1",
# "arg2"
# ]
# }
output_result = session.file_system.read_file("/tmp/output.json")
if output_result.success:
print("Output file content:", output_result.content)
# 出力ファイルの内容: {
# "message": "Hello from uploaded script",
# "args": [
# "arg1",
# "arg2"
# ]
# }
else:
print("Execution failed:", exec_result.error_message)
else:
print("Script write failed:", write_result.error_message)
agent_bay.delete(session)複数ファイルのプロジェクト
from agentbay import AgentBay
from agentbay.session_params import CreateSessionParams
agent_bay = AgentBay(api_key="your-api-key")
session_params = CreateSessionParams(image_id="code_latest")
result = agent_bay.create(session_params)
if result.success:
session = result.session
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}!"
"""
session.file_system.write_file("/workspace/myproject/main.py", main_py)
session.file_system.write_file("/workspace/myproject/utils.py", utils_py)
result = session.command.execute_command("cd /workspace/myproject && python3 main.py")
if result.success:
print("Project output:", result.output)
# プロジェクトの出力: Hello, AgentBay!
else:
print("Execution failed:", result.error_message)
agent_bay.delete(session)ベストプラクティス
長時間実行されるコードのタイムアウト設定
run_code() のデフォルトのタイムアウトは 60 秒です。
重要
ゲートウェイの制限により、各リクエストは 60 秒以内に完了する必要があります。
# デフォルトのタイムアウトは 60 秒
result = session.code.run_code(code, "python")
# カスタムタイムアウトを指定 (最大 60 秒)
result = session.code.run_code(code, "python", timeout_s=60)標準ライブラリのみの使用
CodeSpace には、Python と Node.js の標準ライブラリが含まれています。最高のパフォーマンスと信頼性を得るために、組み込みモジュールのみを使用してください。
Python:os、sys、json、math、datetime、re など。
JavaScript:fs、path、os、crypto など。