本文介紹無影 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.session_id}")
else:
print(f"會話建立失敗: {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 版本: {sys.version}")
print(f"目前的目錄: {os.getcwd()}")
print("Hello from AgentBay!")
"""
result = session.code.run_code(code, "python")
if result.success:
print("輸出:", result.result)
# 輸出:Python 版本:3.11.2 (main, Apr 28 2025, 14:11:48) [GCC 12.2.0]
# 目前的目錄:/workspace
# Hello from AgentBay!
else:
print("執行失敗:", 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"10的階乘: {factorial(10)}")
print(f"斐波那契數列第10項: {fibonacci(10)}")
# 列表推導式
squares = [x**2 for x in range(1, 11)]
print(f"平方數: {squares}")
"""
result = session.code.run_code(code, "python")
if result.success:
print("輸出:", result.result)
# 輸出: 10的階乘:3628800
# 斐波那契數列第10項:55
# 平方數: [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 版本:', process.version);
console.log('目前的目錄:', process.cwd());
// 建立簡單檔案
fs.writeFileSync('/tmp/hello.txt', 'Hello from Node.js!');
console.log('檔案建立成功');
"""
result = session.code.run_code(js_code, "javascript")
if result.success:
print("輸出:", result.result)
# 輸出: Node.js 版本: v18.20.5
# 目前的目錄: /workspace
# 檔案建立成功
else:
print("執行失敗:", 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);
console.log('總和:', sum);
console.log('平均值:', avg);
console.log('平方:', squares);
// 對象操作
const data = {
name: 'AgentBay',
version: '1.0',
features: ['Python', 'JavaScript', 'File I/O']
};
console.log('\\n資料:', JSON.stringify(data, null, 2));
"""
result = session.code.run_code(js_code, "javascript")
if result.success:
print("輸出:", result.result)
# 輸出: 數字: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# 總和: 55
# 平均值: 5.5
# 平方: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
#
# 資料: {
# "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("指令碼上傳成功")
exec_result = session.command.execute_command("python3 /tmp/script.py arg1 arg2")
if exec_result.success:
print("指令碼輸出:", 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_result.content)
# 輸出檔案內容: {
# "message": "Hello from uploaded script",
# "args": [
# "arg1",
# "arg2"
# ]
# }
else:
print("執行失敗:", exec_result.error_message)
else:
print("指令碼寫入失敗:", 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("專案輸出:", result.output)
# 專案輸出: Hello, AgentBay!
else:
print("執行失敗:", 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 等。