代码执行

本文介绍无影 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 标准库。为获得最佳性能和可靠性,请仅使用内置模块:

Pythonossysjsonmathdatetimere 等。
JavaScriptfspathoscrypto 等。