Sandbox 沙箱—Code Interpreter

AgentRun Code Interpreter 是一个强大的代码执行环境,支持在安全的沙箱环境中执行Python代码、管理文件系统、处理数据文件等功能。本文详细介绍Code InterpreterAPI接口。

功能介绍

使用Code Interpreter API可以实现以下功能:

  • 代码执行:支持 Python、JavaScript等语言代码的安全执行

  • 文件管理:上传、下载、移动、删除文件

  • 文件系统操作:目录创建、文件状态查询等

  • 上下文管理:独立的代码执行环境

  • 会话管理:支持并发会话和超时控制

Code Interpreter API分为控制面和数据面两个层面:

  • 控制面OpenAPI:负责代码解释器资源实体的创建和生命周期管理。

  • 数据面OpenAPI:负责具体的代码执行、文件操作等功能调用。所有数据面 API 都需要在请求头中包含 X-AgentRun-Session-ID(其中首字符必须为 a-f 中任一英文字母)。

使用说明

  • AgentRun功能目前处于免费试用中,仅对使用到的函数资源计费。

  • 首次登录AgentRun控制台,请先根据界面提示创建AgentRun服务关联角色AliyunServiceRoleForAgentRun,后续可以通过SDK操作使用。

  • 每个沙箱服务允许并发运行一个会话(session),会话的最长生命周期为 6 小时。此外,通过 sessionIdleTimeoutSeconds 参数,可以设定一个超时时长。如果会话的闲置时间超过该值,它将被提前终止,而无需等待 6 小时的生命周期结束。

使用流程概览

  1. 创建代码解释器服务

  2. 启动会话

  3. 创建执行上下文

  4. 执行代码和文件操作

  5. 清理资源

展开查看使用基本流程示例

# 1. 创建代码解释器(控制面)
curl -X POST "https://agentrun.{regionid}.aliyuncs.com/agents/code-interpreters" \
  -H "Content-Type: application/json" \
  -H "Authorization: <阿里云鉴权签名>" \
  -d '{
    "codeInterpreterName": "my-interpreter",
    "description": "用于数据分析的代码解释器",
    "networkConfiguration": {
      "networkMode": "PUBLIC"
    },
    "cpu": 2,
    "memory": 4096
  }'

# 2. 启动会话(控制面)
curl -X POST "https://agentrun.{regionid}.aliyuncs.com/agents/code-interpreters/{codeInterpreterId}/sessions" \
  -H "Content-Type: application/json" \
  -H "Authorization: <阿里云鉴权签名>" \
  -d '{
    "sessionIdleTimeoutSeconds": 1800
  }'

# 3. 创建上下文(数据面)
curl -X POST "https://{accountid}.agentrun-data.{regionid}.aliyuncs.com/agents/code-interpreters/{codeInterpreterId}/contexts" \
  -H "Content-Type: application/json" \
  -H "X-AgentRun-Session-ID: {sessionId}" \
  -d '{
    "name": "main",
    "config": {}
  }'

# 4. 执行代码(数据面)
curl -X POST "https://{accountid}.agentrun-data.{regionid}.aliyuncs.com/agents/code-interpreters/{codeInterpreterId}/contexts/{contextId}/execute" \
  -H "Content-Type: application/json" \
  -H "X-AgentRun-Session-ID: {sessionId}" \
  -d '{
    "code": "print(\"Hello, World!\")",
    "timeout": 30
  }'

控制面OpenAPI

准备工作

  1. 进入OpenAPI Explorer

  2. 在顶部菜单栏,单击选择云产品,在搜索框搜索并选择AgentRun

  3. 在左侧导航栏,找到调试 > 浏览器沙箱对应的API接口开始使用。

代码解释器管理

API

接口说明

API接口地址

CreateCodeInterpreter

创建一个新的代码解释器服务,用于执行代码解释和运行任务。代码解释器提供 Python 代码执行、数据处理、机器学习等功能。

创建代码解释器

ListCodeInterpreters

获取当前用户的所有代码解释器服务列表,支持按名称等条件过滤,支持分页查询。

获取代码解释器列表

GetCodeInterpreter

根据代码解释器 ID 获取指定代码解释器服务的详细信息,包括配置、状态、资源使用情况等。

获取代码解释器

DeleteCodeInterpreter

删除指定的代码解释器服务,包括其所有相关资源和数据。删除操作不可逆,请谨慎操作。

删除代码解释器

会话管理

说明

该部分接口暂未上线OpenAPI Explorer,可先通过SDK或直接调用API端点使用。

启动会话

接口POST /agents/code-interpreters/{codeInterpreterId}/sessions

请求参数

{
  "sessionIdleTimeoutSeconds": 3600  // 可选:会话超时时间(1-21600秒,默认3600)
}

响应示例

{
  "code": "SUCCESS",
  "requestId": "abc123-def456",
  "data": {
    "codeInterpreterId": "ci-12345678",
    "sessionId": "sess-87654321",
    "status": "READY",
    "createdAt": "2025-01-01T00:00:00Z",
    "lastUpdateAt": "2025-01-01T00:00:00Z",
    "sessionIdleTimeoutSeconds": 3600
  }
}

列出会话

接口GET /agents/code-interpreters/{codeInterpreterId}/sessions?pageNumber=1

获取会话

接口GET /agents/code-interpreters/{codeInterpreterId}/sessions/{sessionId}

停止会话

接口DELETE /agents/code-interpreters/{codeInterpreterId}/sessions/{sessionId}

数据面OpenAPI

准备工作

准备数据面调用BASEURL:https://${阿里云主账号 ID}.agentrun-data.cn-hangzhou.aliyuncs.com/2025-09-10/

在产品控制台右上角单击头像获取阿里云主账号ID。

image

健康检查

代码解释器健康检查

请求语法GET ${BASEURL}/agents/code-interpreters/{codeInterpreterId}/health

查询参数sessionId (string, 必需):会话ID

响应示例

{
  "code": "SUCCESS",
  "requestId": "abc123-def456",
  "data": {
    "status": "OK"
  }
}

文件管理

上传文件

请求语法POST ${BASEURL}/agents/code-interpreters/{codeInterpreterId}/files

请求头X-AgentRun-Session-ID (string, 必需):会话ID

查询参数path (string, 可选):文件路径,URL编码

请求体:multipart/form-data

file: [binary]           // 必需:文件内容(最大100MB)
filename: "data.csv"     // 可选:文件名(未指定path时使用)

文件限制

  • 最大文件大小:100MB

  • 支持的文件类型:文本文件(.txt,.py,.js,.json等)、图片(.jpg,.png,.gif等)、文档(.pdf,.docx等)、数据文件(.csv,.xlsx等)

响应示例

{
  "code": "SUCCESS",
  "requestId": "abc123-def456",
  "data": {
    "fileInfo": {
      "path": "/workspace/data.csv",
      "name": "data.csv",
      "type": "file",
      "size": 1024,
      "permissions": "rw-r--r--",
      "lastModified": "2025-01-01T00:00:00Z",
      "created": "2025-01-01T00:00:00Z"
    },
    "uploadedAt": "2025-01-01T00:00:00Z",
    "checksum": "d41d8cd98f00b204e9800998ecf8427e",
    "mimeType": "text/csv",
    "encoding": "UTF-8",
    "overwritten": false
  }
}

下载文件

请求语法GET /agents/code-interpreters/{codeInterpreterId}/files

请求头

  • X-AgentRun-Session-ID (string, 必需):会话ID

查询参数

  • path (string, 必需):文件路径,URL编码

响应

  • 成功时返回文件二进制流

  • Content-Type: application/octet-stream

  • Content-Length: 文件大小

  • Content-Disposition: 文件下载配置

文件系统操作

列出目录内容

接口GET ${BASEURL}/agents/code-interpreters/{codeInterpreterId}/filesystem

请求头

  • X-AgentRun-Session-ID (string, 必需):会话ID

查询参数

  • path (string, 可选):目录路径

  • depth (integer, 可选):遍历深度

响应示例

{
  "code": "SUCCESS",
  "requestId": "abc123-def456",
  "data": {
    "files": [
      {
        "path": "/workspace/data.csv",
        "name": "data.csv",
        "type": "file",
        "size": 1024,
        "lastModified": "2025-01-01T00:00:00Z"
      },
      {
        "path": "/workspace/scripts",
        "name": "scripts",
        "type": "directory",
        "size": 0,
        "lastModified": "2025-01-01T00:00:00Z"
      }
    ]
  }
}

获取文件或目录信息

接口GET ${BASEURL}/agents/code-interpreters/{codeInterpreterId}/filesystem/stat

请求头

  • X-AgentRun-Session-ID (string, 必需):会话ID

查询参数

  • path (string, 必需):文件或目录路径

创建目录

接口POST ${BASEURL}/agents/code-interpreters/{codeInterpreterId}/filesystem/mkdir

请求头

  • X-AgentRun-Session-ID (string, 必需):会话ID

请求参数

{
  "path": "/workspace/data/temp",    // 必需:要创建的目录路径
  "parents": true,                   // 可选:是否创建父目录(默认true)
  "mode": "0755"                     // 可选:目录权限(默认"0755")
}

特性

  • 幂等操作:目录已存在时返回成功

  • 自动创建父目录(类似 mkdir -p)

  • 支持递归创建多级目录

移动文件或目录

接口POST ${BASEURL}/agents/code-interpreters/{codeInterpreterId}/filesystem/move

请求头

  • X-AgentRun-Session-ID (string, 必需):会话ID

请求参数

{
  "sourcePath": "/workspace/old_file.txt",    // 必需:源路径
  "targetPath": "/workspace/new_file.txt"     // 必需:目标路径
}

特性

  • 支持跨目录移动和同目录重命名

  • 幂等操作:源文件不存在且目标位置有相同名称文件时返回成功

删除文件或目录

接口POST ${BASEURL}/agents/code-interpreters/{codeInterpreterId}/filesystem/remove

请求头

  • X-AgentRun-Session-ID (string, 必需):会话ID

请求参数

{
  "path": "/workspace/temp_file.txt"    // 必需:要删除的路径
}

特性

  • 幂等操作:文件或目录不存在时返回成功

上下文管理

列出上下文

接口GET ${BASEURL}/agents/code-interpreters/{codeInterpreterId}/contexts

请求头

  • X-AgentRun-Session-ID (string, 必需):会话ID

创建上下文

接口POST ${BASEURL}/agents/code-interpreters/{codeInterpreterId}/contexts

请求头

  • X-AgentRun-Session-ID (string, 必需):会话ID

请求参数

{
  "name": "main",          // 必需:上下文名称
  "config": {}             // 可选:上下文配置
}

响应示例

{
  "code": "SUCCESS",
  "requestId": "abc123-def456",
  "data": {
    "id": "ctx-12345678",
    "name": "main",
    "status": "READY"
  }
}

在上下文中执行代码

接口POST ${BASEURL}/agents/code-interpreters/{codeInterpreterId}/contexts/{contextId}/execute

请求头

  • X-AgentRun-Session-ID (string, 必需):会话ID

请求参数

{
  "code": "print('Hello, World!')",    // 必需:要执行的代码
  "timeout": 30                        // 可选:执行超时时间(秒,默认30)
}

响应示例

{
  "code": "SUCCESS",
  "requestId": "abc123-def456",
  "data": {
    "stdout": "Hello, World!\n",
    "stderr": "",
    "exit_code": 0,
    "execution_time": 0.1
  }
}

重启上下文

接口POST ${BASEURL}/agents/code-interpreters/{codeInterpreterId}/contexts/{contextId}/restart

请求头

  • X-AgentRun-Session-ID (string, 必需):会话ID

说明:重启会清除上下文中的所有变量和状态

删除上下文

接口DELETE ${BASEURL}/agents/code-interpreters/{codeInterpreterId}/contexts/{contextId}

请求头

  • X-AgentRun-Session-ID (string, 必需):会话ID

常见错误码

状态码

错误说明

处理建议

400

请求参数错误

检查请求参数格式和必需字段

401

未授权访问

检查认证信息和权限配置

404

资源未找到

确认资源ID和路径正确

409

资源冲突

文件已存在或状态冲突

413

文件过大

文件超过100 MB限制,建议分段上传或压缩

500

内部服务器错误

联系技术支持

507

存储空间不足

清理文件后重试

错误响应格式

{
  "code": "ERROR_CODE",
  "requestId": "abc123-def456-****",
  "message": "详细错误信息"
}

重试策略

对于以下错误建议实施重试:

  • 5xx 服务器错误:指数退避重试

  • 429 限流错误:等待后重试

  • 507 存储空间不足:清理后重试

更多信息

资源管理

  1. 及时清理资源

    • 完成任务后删除不需要的文件

    • 不再使用的上下文和会话应及时删除

    • 监控存储空间使用情况

  2. 合理配置超时时间

    • 短期任务:使用较短的超时时间(5-10分钟)

    • 长期任务:适当延长超时时间(30分钟-6小时)

代码执行

  1. 错误处理

import traceback

try:
    # 你的代码
    result = some_function()
    print(f"执行成功: {result}")
except Exception as e:
    print(f"执行失败: {str(e)}")
    traceback.print_exc()
  1. 大数据处理

    • 使用 pandas 分块读取大文件

    • 及时释放内存中的大对象

    • 使用生成器处理大量数据

  2. 文件操作

import os
import pandas as pd

# 检查文件是否存在
if os.path.exists('/workspace/data.csv'):
    df = pd.read_csv('/workspace/data.csv')
    print(f"读取了 {len(df)} 行数据")

安全考虑

  1. 输入验证

    • 验证上传文件的类型和大小

    • 检查文件路径防止目录遍历攻击

  2. 权限控制

    • 使用最小权限原则配置 executionRoleArn

    • 定期审查和更新凭证

  3. 数据保护

    • 敏感数据使用后及时删除

    • 避免在代码中硬编码敏感信息

更多示例

以下提供一个完整的数据分析工作流示例,更多示例,请前往OpenAPI Explorer查看和调试。

数据分析工作流示例

import requests
import json
import time

# 配置
BASE_URL_CONTROL = "https://agentrun.{regionid}.aliyuncs.com"
BASE_URL_DATA = "https://{accountid}.agentrun-data.{regionid}.aliyuncs.com"
headers = {
    "Content-Type": "application/json",
    "Authorization": "Bearer YOUR_TOKEN"
}

# 1. 创建代码解释器
def create_interpreter():
    payload = {
        "codeInterpreterName": "data-analysis-interpreter",
        "description": "用于数据分析的代码解释器",
        "networkConfiguration": {
            "networkMode": "PUBLIC"
        },
        "cpu": 4,
        "memory": 8192,
        "sessionIdleTimeoutSeconds": 3600
    }
    
    response = requests.post(
        f"{BASE_URL_CONTROL}/agents/code-interpreters",
        headers=headers,
        data=json.dumps(payload)
    )
    
    result = response.json()
    interpreter_id = result["data"]["codeInterpreterId"]
    
    # 等待创建完成
    while True:
        status_response = requests.get(
            f"{BASE_URL_CONTROL}/agents/code-interpreters/{interpreter_id}",
            headers=headers
        )
        status = status_response.json()["data"]["status"]
        
        if status == "READY":
            break
        elif status in ["CREATE_FAILED", "DELETE_FAILED"]:
            raise Exception(f"创建失败: {status}")
        
        time.sleep(10)
    
    return interpreter_id

# 2. 启动会话
def start_session(interpreter_id):
    payload = {
        "sessionIdleTimeoutSeconds": 3600
    }
    
    response = requests.post(
        f"{BASE_URL_CONTROL}/agents/code-interpreters/{interpreter_id}/sessions",
        headers=headers,
        data=json.dumps(payload)
    )
    
    result = response.json()
    return result["data"]["sessionId"]

# 3. 创建执行上下文
def create_context(interpreter_id, session_id):
    headers_with_session = headers.copy()
    headers_with_session["X-AgentRun-Session-ID"] = session_id
    
    payload = {
        "name": "data-analysis",
        "config": {}
    }
    
    response = requests.post(
        f"{BASE_URL_DATA}/agents/code-interpreters/{interpreter_id}/contexts",
        headers=headers_with_session,
        data=json.dumps(payload)
    )
    
    result = response.json()
    return result["data"]["id"]

# 4. 上传数据文件
def upload_data_file(interpreter_id, session_id, file_path):
    headers_with_session = {
        "X-AgentRun-Session-ID": session_id,
        "Authorization": headers["Authorization"]
    }
    
    with open(file_path, 'rb') as f:
        files = {'file': f}
        response = requests.post(
            f"{BASE_URL_DATA}/agents/code-interpreters/{interpreter_id}/files",
            headers=headers_with_session,
            files=files,
            params={'path': '/workspace/data.csv'}
        )
    
    return response.json()

# 5. 执行数据分析代码
def execute_analysis(interpreter_id, session_id, context_id):
    headers_with_session = headers.copy()
    headers_with_session["X-AgentRun-Session-ID"] = session_id
    
    analysis_code = """
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

# 读取数据
df = pd.read_csv('/workspace/data.csv')
print(f"数据形状: {df.shape}")
print(f"数据列: {df.columns.tolist()}")

# 基本统计信息
print("\\n基本统计信息:")
print(df.describe())

# 检查缺失值
print(f"\\n缺失值情况:")
print(df.isnull().sum())

# 数据可视化
if len(df.columns) >= 2:
    plt.figure(figsize=(10, 6))
    
    # 如果是数值列,创建散点图
    numeric_cols = df.select_dtypes(include=[np.number]).columns
    if len(numeric_cols) >= 2:
        plt.scatter(df[numeric_cols[0]], df[numeric_cols[1]])
        plt.xlabel(numeric_cols[0])
        plt.ylabel(numeric_cols[1])
        plt.title('数据散点图')
        plt.savefig('/workspace/analysis_plot.png', dpi=150, bbox_inches='tight')
        print("\\n已生成散点图: /workspace/analysis_plot.png")
    
    plt.close()

# 保存处理后的数据
if 'processed_data' not in locals():
    processed_data = df.copy()
    
# 数据清洗示例
processed_data = processed_data.dropna()
processed_data.to_csv('/workspace/processed_data.csv', index=False)
print(f"\\n已保存处理后的数据: /workspace/processed_data.csv")
print(f"处理后数据形状: {processed_data.shape}")
"""
    
    payload = {
        "code": analysis_code,
        "timeout": 120
    }
    
    response = requests.post(
        f"{BASE_URL_DATA}/agents/code-interpreters/{interpreter_id}/contexts/{context_id}/execute",
        headers=headers_with_session,
        data=json.dumps(payload)
    )
    
    result = response.json()
    print("代码执行结果:")
    print(result["data"])
    
    return result

# 6. 下载结果文件
def download_result(interpreter_id, session_id, file_path, local_path):
    headers_with_session = {
        "X-AgentRun-Session-ID": session_id,
        "Authorization": headers["Authorization"]
    }
    
    response = requests.get(
        f"{BASE_URL_DATA}/agents/code-interpreters/{interpreter_id}/files",
        headers=headers_with_session,
        params={'path': file_path}
    )
    
    if response.status_code == 200:
        with open(local_path, 'wb') as f:
            f.write(response.content)
        print(f"文件已下载到: {local_path}")
    else:
        print(f"下载失败: {response.status_code}")

# 7. 清理资源
def cleanup(interpreter_id, session_id, context_id):
    headers_with_session = headers.copy()
    headers_with_session["X-AgentRun-Session-ID"] = session_id
    
    # 删除上下文
    requests.delete(
        f"{BASE_URL_DATA}/agents/code-interpreters/{interpreter_id}/contexts/{context_id}",
        headers=headers_with_session
    )
    
    # 停止会话
    requests.delete(
        f"{BASE_URL_CONTROL}/agents/code-interpreters/{interpreter_id}/sessions/{session_id}",
        headers=headers
    )
    
    # 删除代码解释器(可选)
    # requests.delete(
    #     f"{BASE_URL_CONTROL}/agents/code-interpreters/{interpreter_id}",
    #     headers=headers
    # )

# 主工作流
def main():
    try:
        # 1. 创建代码解释器
        print("创建代码解释器...")
        interpreter_id = create_interpreter()
        print(f"代码解释器创建成功: {interpreter_id}")
        
        # 2. 启动会话
        print("启动会话...")
        session_id = start_session(interpreter_id)
        print(f"会话启动成功: {session_id}")
        
        # 3. 创建执行上下文
        print("创建执行上下文...")
        context_id = create_context(interpreter_id, session_id)
        print(f"上下文创建成功: {context_id}")
        
        # 4. 上传数据文件
        print("上传数据文件...")
        upload_result = upload_data_file(interpreter_id, session_id, "local_data.csv")
        print("文件上传成功")
        
        # 5. 执行数据分析
        print("执行数据分析...")
        analysis_result = execute_analysis(interpreter_id, session_id, context_id)
        
        # 6. 下载结果文件
        print("下载结果文件...")
        download_result(interpreter_id, session_id, "/workspace/processed_data.csv", "processed_data.csv")
        download_result(interpreter_id, session_id, "/workspace/analysis_plot.png", "analysis_plot.png")
        
        print("数据分析工作流完成!")
        
    except Exception as e:
        print(f"工作流执行失败: {str(e)}")
    
    finally:
        # 7. 清理资源
        if 'interpreter_id' in locals() and 'session_id' in locals():
            print("清理资源...")
            cleanup(interpreter_id, session_id, context_id)
            print("资源清理完成")

if __name__ == "__main__":
    main() 

以上示例展示了:

  • 代码解释器的完整生命周期管理

  • 数据文件的上传和下载

  • 复杂数据分析代码的执行

  • 结果文件的处理

  • 适当的错误处理和资源清理