全部產品
Search
文件中心

Function Compute:Code Interpreter代碼解譯器

更新時間:Jun 04, 2026

Code Interpreter 是一個強大的代碼執行沙箱環境,支援在安全的沙箱環境中執行Python代碼、管理檔案系統、執行shell命令等功能。本文詳細介紹Code Interpreter的API介面。

功能介紹

使用Code Interpreter API可以實現以下功能:

  • 代碼執行:支援 Python、JavaScript等語言代碼的安全執行

  • 檔案管理:上傳、下載、移動、刪除檔案

  • 檔案系統操作:目錄建立、檔案狀態查詢等

  • 上下文管理:獨立的代碼執行環境

  • 會話管理:支援並發會話和逾時控制

Code Interpreter API分為控制面和資料面兩個層面:

  • 控制面OpenAPI:負責代碼解譯器資源實體的建立和生命週期管理。

  • 資料面OpenAPI:負責具體的代碼執行、檔案操作等功能調用。

使用說明

  • 首次登入AgentRun控制台,請先根據介面提示建立AgentRun服務關聯角色AliyunServiceRoleForAgentRun,後續可以通過SDK操作使用。

  • 沙箱模板定義一組沙箱執行個體的基礎配置;沙箱執行個體則是具體執行代碼任務的沙箱環境,一個沙箱執行個體最長生命週期為 6 小時。此外,通過 sandboxIdleTimeoutInSeconds 參數,可以設定一個逾時時間長度。如果會話的淺休眠(原閑置)時間超過該值,它將被提前終止,而無需等待 6 小時的生命週期結束。

使用流程概覽

  1. 建立代碼解譯器模板

  2. 啟動代碼解譯器沙箱執行個體

  3. 建立執行內容

  4. 執行代碼

控制面OpenAPI

準備工作

  1. 進入OpenAPI Explorer

  2. 在頂部功能表列,單擊選擇雲產品,在搜尋方塊搜尋並選擇AgentRun

  3. 在左側導覽列,找到對應的API介面開始使用。

範本管理員

以上述OpenAPI門戶連結中的API文檔為準。

資料面OpenAPI

準備工作

準備資料面調用BASEURL:https://${阿里雲主帳號 ID}.agentrun-data.ap-southeast-1.aliyuncs.com/

在產品控制台右上方單擊頭像擷取阿里雲主帳號ID。

沙箱執行個體管理

說明

該部分介面暫未上線OpenAPI Explorer,可先通過SDK或直接調用API端點使用。

建立Sandbox執行個體

請求路徑:POST ${BASEURL}/sandboxes

要求標頭:X-Acs-Parent-Id: ${阿里雲主帳號ID}

  • Content-Type: application/json

請求體:application/json

{
  "templateName": "string",                          // 必需:模板名稱,系統內部通過 templateName 查詢 template_id
  "sandboxId": "string",                             // 可選:自訂沙箱 ID,用於端到端 tracing。如果不指定,系統會自動產生 ULID 格式的 ID
}

響應樣本:

{
  "sandboxId": "01JCED8Z9Y6XQVK8M2NRST5WXY",
  "templateId": "01JCED8Z9Y6XQVK8M2NRST5ABC",
  "templateName": "python-sandbox",
  "templateType": "CodeInterpreter",
  "status": "READY",
  "sandboxIdleTimeoutInSeconds": 3600,
  "createdAt": "2024-12-02T10:30:00Z",
  "lastUpdatedAt": "2024-12-02T10:30:15Z",
  "metadata": {
    "fcSessionDetails": {
      "sessionId": "1234567890abcdef",
      "sessionStatus": "Active",
      "sessionIdleTimeoutInSeconds": 3600,
      "functionName": "sandbox-function",
      "qualifier": "LATEST",
      "containerId": "container-123",
      "createdTime": "2024-12-02T10:30:00Z",
      "lastModifiedTime": "2024-12-02T10:30:15Z",
      "sessionAffinityType": "HEADER_FIELD"
    }
  }
}

停止Sandbox執行個體

請求路徑:POST ${BASEURL}/sandboxes/{sandboxId}/stop

要求標頭:X-Acs-Parent-Id: ${阿里雲主帳號ID}

路徑參數:

  • sandboxId(string, 必需): 沙箱 ID

請求體:

響應樣本:

{
  "sandboxId": "01JCED8Z9Y6XQVK8M2NRST5WXY",
  "templateId": "01JCED8Z9Y6XQVK8M2NRST5ABC",
  "templateName": "python-sandbox",
  "templateType": "CodeInterpreter",
  "status": "TERMINATED",
  "sandboxIdleTimeoutInSeconds": 3600,
  "createdAt": "2024-12-02T10:30:00Z",
  "lastUpdatedAt": "2024-12-02T11:00:00Z",
  "endedAt": "2024-12-02T11:00:00Z"
}

說明:

  • 停止 Sandbox 會刪除 FC Session 並將資料庫狀態更新為 TERMINATED

  • 操作具有等冪性,如果 Sandbox 已經是 TERMINATED 狀態,直接返回

  • 會設定 endedAt 時間戳記

刪除Sandbox執行個體

請求路徑:DELETE ${BASEURL}/sandboxes/{sandboxId}

要求標頭:X-Acs-Parent-Id: ${阿里雲主帳號ID}

路徑參數:

  • sandboxId (string, 必需):沙箱 ID

請求體:

響應樣本:

{
  "sandboxId": "01JCED8Z9Y6XQVK8M2NRST5WXY",
  "templateId": "01JCED8Z9Y6XQVK8M2NRST5ABC",
  "templateName": "python-sandbox",
  "templateType": "CodeInterpreter",
  "status": "READY|TERMINATED",
  "sandboxIdleTimeoutInSeconds": 3600,
  "createdAt": "2024-12-02T10:30:00Z",
  "lastUpdatedAt": "2024-12-02T11:30:00Z",
  "endedAt": "2024-12-02T11:00:00Z"
}

刪除 Sandbox 會執行以下操作:

  • 檢查 Sandbox 是否存在

  • 如果 Sandbox 是 READY 狀態,先調用 StopSandbox 刪除 FC Session

  • 會返回刪除前 Sandbox 的狀態

狀態說明

Sandbox 的狀態流轉:

  • CREATING: 建立中

  • READY: 就緒,可以使用

  • TERMINATED: 已停止(通過 StopSandbox 介面)

錯誤響應

所有介面在出現錯誤時返回統一的錯誤格式:

{
  "error": {
    "code": "ERROR_CODE",
    "message": "錯誤描述資訊"
  }
}

常見錯誤碼:

  • 400 Bad Request:請求參數錯誤

  • 404 Not Found:Sandbox 不存在

  • 500 Internal Server Error:伺服器內部錯誤

健全狀態檢查

檢查服務健康狀態

請求文法GET ${BASEURL}/sandboxes/{sandboxId}/health

要求標頭X-Acs-Parent-Id: ${阿里雲主帳號ID}

查詢參數:無

響應樣本

{
  "status": "ok",
  "service": "sandbox-code-interpreter",
  "version": "v1",
  "timestamp": "2025-11-15T09:45:01.068104+08:00",
  "uptime": 1142269582541
}

上下文管理

列出所有上下文

請求文法GET ${BASEURL}/sandboxes/{sandboxId}/contexts

要求標頭X-Acs-Parent-Id: ${阿里雲主帳號ID}

查詢參數:無

響應樣本:

[
  {
    "id": "kernel-12345-67890",
    "language": "python",
    "cwd": "/tmp/sandbox/home/user"
  }
]

建立新上下文

請求文法POST ${BASEURL}/sandboxes/{sandboxId}/contexts

要求標頭X-Acs-Parent-Id: ${阿里雲主帳號ID}

  • Content-Type: application/json

請求體application/json

{
  "language": "python",  // 必需:python 或 javascript
  "cwd": "/tmp/sandbox/home/user"  // 可選:工作目錄
}

響應樣本:

{
  "id": "271f70d5-9065-4403-8ea3-4d541f7d2bb8",
  "language": "python",
  "cwd": "/home/user"
}

擷取上下文詳情

請求文法GET ${BASEURL}/sandboxes/{sandboxId}/contexts/{contextId}

路徑參數

  • contextId (string, 必需): 內容相關的唯一識別碼

要求標頭X-Acs-Parent-Id: ${阿里雲主帳號ID}

查詢參數:無

響應樣本

{
  "id": "271f70d5-9065-4403-8ea3-4d541f7d2bb8",
  "language": "python",
  "cwd": "/home/user"
}

刪除上下文

請求文法DELETE ${BASEURL}/sandboxes/{sandboxId}/contexts/{contextId}

路徑參數

  • contextId (string, 必需):內容相關的唯一識別碼

要求標頭X-Acs-Parent-Id: ${阿里雲主帳號ID}

查詢參數:無

響應:204 No Content(無響應體)

檔案系統操作

讀取檔案內容

請求文法:GET ${BASEURL}/sandboxes/{sandboxId}/files

要求標頭:X-Acs-Parent-Id: ${阿里雲主帳號ID}

查詢參數:

  • path (string, 必需): 檔案路徑(支援文字檔和二進位檔案)

響應樣本

{
  "name": "example.txt",
  "type": "file",
  "path": "/workspace/example.txt",
  "size": 1024,
  "mode": 420,
  "permissions": "-rw-r--r--",
  "owner": "user",
  "group": "group",
  "modifiedTime": "2025-11-15T10:30:00Z",
  "content": "Hello, World!\nThis is a text file.",
  "encoding": "utf-8"
}

說明:

  • 文字檔:encoding"utf-8"content 為 UTF-8 常值內容

  • 二進位檔案:encoding"base64"content 為 base64 編碼的內容

寫入檔案內容

請求文法: POST ${BASEURL}/sandboxes/{sandboxId}/files

要求標頭X-Acs-Parent-Id: ${阿里雲主帳號ID}

  • Content-Type: application/json

請求體: application/json

{
  "path": "example.txt",  // 必需:檔案路徑(不支援隱藏檔案)
  "content": "Hello, World!\nThis is a text file.",  // 必需:UTF-8 常值內容
  "encoding": "utf-8"  // 可選:預設為 utf-8
}

檔案限制:

  • 只支援文字檔副檔名(.txt, .py, .json, .md 等)

  • 不允許建立以 . 開頭的隱藏檔案

  • 自動建立父目錄(如果不存在)

  • 預設檔案許可權:0644

{
  "path": "/home/user/example.txt",
  "size": 25
}

列出目錄內容

請求文法: GET ${BASEURL}/sandboxes/{sandboxId}/filesystem

要求標頭X-Acs-Parent-Id: ${阿里雲主帳號ID}

查詢參數

  • path (string, 可選): 目錄路徑(預設為目前的目錄)

  • depth (integer, 可選): 遍曆深度(預設為 1,最小值為 1)

響應樣本:

{
  "path": "/home/user",
  "entries": [
    {
      "name": "example.txt",
      "type": "file",
      "path": "/tmp/code-interpreter-sandbox/home/user/example.txt",
      "size": 1024,
      "mode": 420,
      "permissions": "-rw-r--r--",
      "owner": "user",
      "group": "group",
      "modifiedTime": "2025-11-15T10:30:00Z"
    }
  ]
}

擷取檔案或目錄資訊

請求文法GET ${BASEURL}/sandboxes/{sandboxId}/filesystem/stat

要求標頭X-Acs-Parent-Id: ${阿里雲主帳號ID}

查詢參數

  • path (string, 必需): 檔案或目錄路徑

響應樣本

{
  "entry": {
    "name": "example.py",
    "type": "file",
    "path": "/workspace/example.py",
    "size": 1024,
    "mode": 420,
    "permissions": "-rw-r--r--",
    "owner": "user",
    "group": "group",
    "modifiedTime": "2025-11-15T10:30:00Z"
  }
}

下載檔案

請求文法GET ${BASEURL}/sandboxes/{sandboxId}/filesystem/download

要求標頭X-Acs-Parent-Id: ${阿里雲主帳號ID}

查詢參數

  • path (string, 必需): 檔案路徑

響應

  • Content-Type: 檔案的 MIME 類型

  • Content-Disposition: attachment; filename="example.txt"

  • Content-Length: 檔案大小(位元組)

  • 響應體: 檔案二進位流

說明: 只支援檔案下載,不支援目錄

建立目錄

請求文法POST ${BASEURL}/sandboxes/{sandboxId}/filesystem/mkdir

要求標頭X-Acs-Parent-Id: ${阿里雲主帳號ID}

  • Content-Type: application/json

請求體application/json

{
  "path": "/tmp/home/user/testDir"  // 必需:目錄路徑
}

說明:

  • 支援等冪操作:如果目錄已存在,返回 200

  • 如果父目錄不存在,自動建立它們(類似 mkdir -p)

  • 支援遞迴目錄建立

響應樣本:

{
  "entry": {
    "name": "testDir",
    "type": "directory",
    "path": "/home/user/test_dir",
    "size": 0,
    "mode": 493,
    "permissions": "drwxr-xr-x",
    "owner": "user",
    "group": "group",
    "modifiedTime": "2025-11-15T10:30:00Z"
  }
}

移動或重新命名檔案/目錄

請求文法POST ${BASEURL}/sandboxes/{sandboxId}/filesystem/move

要求標頭X-Acs-Parent-Id: ${阿里雲主帳號ID}

  • Content-Type: application/json

請求體application/json

{
  "source": "/workspace/old_name.txt",  // 必需:源檔案或目錄路徑
  "destination": "/workspace/new_name.txt"  // 必需:目標檔案或目錄路徑
}

說明:

  • 支援等冪操作:如果源檔案不存在且目標已存在同名檔案,返回 200

  • 支援跨目錄移動和同目錄重新命名

響應樣本:

{
  "entry": {
    "name": "new_name.txt",
    "type": "file",
    "path": "/workspace/new_name.txt",
    "size": 1024,
    "mode": 420,
    "permissions": "-rw-r--r--",
    "owner": "user",
    "group": "group",
    "modifiedTime": "2025-11-15T10:30:00Z"
  }
}

刪除檔案或目錄

請求文法POST ${BASEURL}/sandboxes/{sandboxId}/filesystem/remove

要求標頭X-Acs-Parent-Id: ${阿里雲主帳號ID}

  • Content-Type: application/json

請求體application/json

{
  "path": "/home/user/test_dir"  // 必需:檔案或目錄路徑
}

說明

  • 支援等冪操作:如果檔案或目錄不存在,返回 200

  • 支援遞迴刪除目錄

響應樣本

{
  "entry": {
    "name": "testDir",
    "type": "directory",
    "path": "/home/user/test_dir",
    "size": 0,
    "mode": 493,
    "permissions": "drwxr-xr-x",
    "owner": "user",
    "group": "group",
    "modifiedTime": "2025-11-15T10:30:00Z"
  }
}

上傳檔案

請求文法POST ${BASEURL}/sandboxes/{sandboxId}/filesystem/upload

要求標頭X-Acs-Parent-Id: ${阿里雲主帳號ID}

  • Content-Type: multipart/form-data

請求體multipart/form-data

file: [binary]           // 必需:檔案內容(最大 100MB)
path: "uploads/example.txt"     // 可選:目標檔案路徑(如果不提供則使用檔案名稱)
current_path: "."       // 可選:目前的目錄路徑(當 path 未提供時使用)

檔案限制

  • 最大檔案大小:100MB

  • 只支援檔案上傳,不支援目錄建立

  • 自動建立父目錄(如果不存在)

響應樣本:

{
  "path": "uploads/example.txt",
  "size": 1024
}

代碼執行

同步執行代碼

請求文法POST ${BASEURL}/sandboxes/{sandboxId}/contexts/execute

要求標頭X-Acs-Parent-Id: ${阿里雲主帳號ID}

  • Content-Type: application/json

請求體application/json

{
  "contextId": "kernel-12345-67890",  // 可選:內容識別碼(如果提供,則不需要 language)
  "language": "python",  // 可選:程式設計語言類型(僅在未提供 contextId 時需要)
  "code": "print('hello')",  // 必需:要執行的代碼
  "timeout": 30  // 可選:執行逾時時間(秒,預設 30,最大 30)
}

響應樣本:

{
  "results": [
    {
      "type": "stdout",
      "text": "hello"
    },
    {
      "type": "result",
      "text": "None"
    },
    {
      "type": "endOfExecution",
      "status": "ok"
    }
  ],
  "contextId": "kernel-12345-67890"
}

終端執行

同步執行命令

同步執行命令

請求文法: POST ${BASEURL}/sandboxes/{sandboxId}/processes/cmd

要求標頭X-Acs-Parent-Id: ${阿里雲主帳號ID}

  • Content-Type: application/json

請求體: application/json

{
  "command": "ls -la /home/user",  // 必需:要執行的命令
  "cwd": "/tmp/code-interpreter-sandbox/home/user"  // 可選:工作目錄
}

說明:

  • 硬逾時限制:資料面網關強制執行的 30 秒最大執行時間

  • 直接響應:在 HTTP 響應中返回完整的命令執行結果

  • 無需上下文:命令執行不需要上下文

  • 使用情境:簡單命令、系統檢查、檔案操作

  • 互動式終端:請使用 /processes/tty WebSocket 端點

響應樣本:

{
  "executionId": "tty_exec_001",
  "status": "completed",
  "result": {
    "exitCode": 0,
    "stdout": "total 24\ndrwxr-xr-x 3 user user 4096 Jan 15 10:30 .",
    "stderr": "",
    "cwd": "/tmp/code-interpreter-sandbox/home/user",
    "executionTimeMs": 150
  },
  "executionTimeMs": 150
}

WebSocket互動式終端端點

請求文法: GET ${BASEURL}/sandboxes/{sandboxId}/processes/tty?protocol=json&tenantId={阿里雲主帳號ID}

要求標頭

  • Connection: Upgrade (必需)

  • Upgrade: websocket (必需)

  • Sec-WebSocket-Key: {key} (必需)

  • Sec-WebSocket-Version: 13 (必需)

查詢參數:

  • protocol (string, 可選): WebSocket 通訊的協議模式

    • json (預設): 結構化訊息的 JSON 訊息格式

    • text: 用於 xterm.js 相容性的直接文字資料流格式

響應: 101 Switching Protocols

說明

  • 互動式終端:完整的雙向終端通訊

  • 即時 I/O:帶終端控制序列的即時輸入/輸出流

  • 會話持久化:工作目錄、環境變數和命令歷史

  • 終端功能:支援顏色、游標控制、終端調整大小

  • 無需上下文:TTY 執行不需要上下文

  • 使用情境:互動式 shell 會話、系統管理、調試

心跳保活機制:

  • 心跳間隔:用戶端每 30 秒發送一次 ping

  • 逾時檢測:伺服器在 2 分鐘內無心跳後關閉串連

  • 逾時警告:伺服器在 90 秒時發送警告

  • 會話管理:中斷連線時 TTY 進程被銷毀,重新串連時建立新會話

  • 自動重連:用戶端應實現自動重連和會話重建

會話行為:

  • 串連丟失:TTY 進程立即終止,所有正在啟動並執行命令停止

  • 重新串連:用戶端重新串連到新的 TTY 會話,工作目錄和環境重設

  • 狀態丟失:命令歷史、正在啟動並執行進程和工作階段狀態丟失

  • 緩解措施:使用 screen/tmux 建立在中斷連線後仍能保持的持久會話

訊息類型(JSON 模式):

  • input: 向終端發送輸入(擊鍵、命令)

  • output: 從終端接收輸出(stdout、stderr)

  • resize: 調整終端尺寸

  • status: 終端狀態變化

  • ping/pong: 串連保活心跳

  • connectionEstablished: 串連確認,包含會話資訊

  • timeoutWarning: 連線逾時前的警告

  • connectionClosing: 串連關閉通知

JSON 模式訊息樣本:

發送輸入:

{
  "type": "input",
  "data": "ls -la\n"
}

接收輸出:

{
  "type": "output",
  "data": "total 24\ndrwxr-xr-x 3 user user 4096 Jan 15 10:30 .\r\n",
  "stream": "stdout"
}

調整大小:

{
  "type": "resize",
  "rows": 24,
  "cols": 80
}

文字模式 (?protocol=text - 用於 xterm.js):

  • 發送:直接文本資料(擊鍵、命令)

  • 接收:直接終端輸出(帶 ANSI 轉義碼)

  • 調整大小:二進位訊息(8 位元組:4 位元組行數 + 4 位元組列數,大端序)

  • 無 JSON 封裝,延遲更低,效能更好

進程管理

列出所有進程

請求文法: GET ${BASEURL}/sandboxes/{sandboxId}/processes

要求標頭X-Acs-Parent-Id: ${阿里雲主帳號ID}

查詢參數: 無

響應樣本

{
  "items": [
    {
      "processId": 12345,
      "status": "running",
      "command": "python script.py",
      "tag": "my-process",
      "createdAt": "2025-11-15T10:30:00Z"
    }
  ],
  "total": 1
}

按PID擷取進程詳情

請求文法: GET ${BASEURL}/sandboxes/{sandboxId}/processes/{pid}

路徑參數:

  • pid (integer, 必需):進程 ID

要求標頭X-Acs-Parent-Id: ${阿里雲主帳號ID}

查詢參數: 無

響應樣本

{
  "processId": 12345,
  "status": "running",
  "command": "python script.py",
  "tag": "my-process",
  "createdAt": "2025-11-15T10:30:00Z",
  "working_dir": "/tmp/sandbox/home/user",
  "environment": {
    "PATH": "/usr/bin:/bin",
    "HOME": "/tmp/sandbox/home/user"
  },
  "resourceUsage": {
    "cpuPercent": 10.5,
    "memoryMb": 128.0
  }
}

強制停止進程

請求文法: DELETE ${BASEURL}/sandboxes/{sandboxId}/processes/{pid}

路徑參數:

  • pid (integer, 必需):要停止的進程 ID

要求標頭X-Acs-Parent-Id: ${阿里雲主帳號ID}

查詢參數: 無

說明:

  • 通過發送 SIGTERM 訊號強制停止進程,如果失敗,則發送 SIGKILL 訊號

  • 這是一個破壞性操作,將立即終止進程

響應樣本

{
  "pid": 12345,
  "stopped": true,
  "stopped_at": "2025-11-15T10:35:00Z",
  "message": "Process stopped successfully"
}

錯誤響應

所有錯誤格式都應遵循以下格式:

{
  "error": {
    "code": "ERROR_CODE",
    "message": "人類可讀的錯誤訊息",
    "details": {
      // 附加錯誤詳情(可選)
    }
  }
}

常見錯誤碼

狀態代碼

錯誤說明

處理建議

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. 資料保護

    • 敏感性資料使用後及時刪除

    • 避免在代碼中寫入程式碼敏感資訊