Code Interpreter is a secure sandbox environment that lets you run Python code, manage the file system, and execute shell commands. This topic describes the API operations for Code Interpreter.
Features
The Code Interpreter API supports the following features:
-
Code execution: Securely execute code in languages such as Python and JavaScript.
-
File management: Upload, download, move, and delete files.
-
File system operations: Create directories and query file status.
-
Context Management: An independent code execution environment
-
Session management: Manage concurrent sessions and control timeouts.
The Code Interpreter API is divided into a control plane and a data plane:
-
Control plane OpenAPI: Manages the creation and lifecycle of Code Interpreter resources.
-
Data plane OpenAPI: Handles calls for specific functions, such as code execution and file operations.
Usage notes
-
When you log on to the AgentRun console for the first time, create the
AliyunServiceRoleForAgentRunservice-linked role as prompted. You can then use the SDK to perform operations. -
On the Runtimes and Sandboxes tab in the console, select Sandbox. Click Create Sandbox Template and select Code Interpreter Sandbox to create a template.
-
A sandbox template defines the basic configuration for a set of sandbox instances. A sandbox instance is the environment where code tasks are executed. The maximum lifecycle of a sandbox instance is 6 hours. You can also use the
sandboxIdleTimeoutInSecondsparameter to set a timeout period. If a session is idle for longer than the specified period, the instance is terminated before the end of its 6-hour lifecycle.
Usage flow overview
-
Create a Code Interpreter template
-
Start a Code Interpreter sandbox instance
-
Create an execution context
-
Execute code
Control plane OpenAPI
Preparations
-
Go to OpenAPI Explorer.
-
On the top menu bar, click Select Product. Then, search for and select AgentRun.
-
In the navigation pane on the left, you can find the API operations under .
Template management
For more information, see the API documentation on the OpenAPI portal.
Data plane OpenAPI
Preparations
Use the following base URL for the data plane: https://${Alibaba Cloud account ID}.agentrun-data.ap-southeast-1.aliyuncs.com/
You can click your profile picture in the upper-right corner of the product console to obtain your Alibaba Cloud account ID.
Sandbox instance management
These API operations are not yet available in OpenAPI Explorer. You can use the SDK or call the API endpoints directly.
Create a sandbox instance
URI of the request: POST ${BASEURL}/sandboxes
Request header: X-Acs-Parent-Id: ${Alibaba Cloud account ID}
-
Content-Type: application/json
Request body: application/json
{
"templateName": "string", // Required. The template name. The system queries the template_id based on the templateName.
"sandboxId": "string", // Optional. A custom sandbox ID for end-to-end tracing. If not specified, the system automatically generates an ID in ULID format.
}
Response example:
{
"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"
}
}
}
Stop a sandbox instance
URI of the request: POST ${BASEURL}/sandboxes/{sandboxId}/stop
Request header: X-Acs-Parent-Id: ${Alibaba Cloud account ID}
Path parameters:
-
sandboxId(string, Required): The sandbox ID.
Request body: None
Example response:
{
"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"
}
Note:
-
Stopping a sandbox deletes the FC session and updates the database status to
TERMINATED. -
This operation is idempotent. If the sandbox is already in the
TERMINATEDstate, a response is returned immediately. -
The
endedAttimestamp is set.
Delete a sandbox instance
URI of the request: DELETE ${BASEURL}/sandboxes/{sandboxId}
Request header: X-Acs-Parent-Id: ${Alibaba Cloud account ID}
Path parameters:
-
sandboxId(string, Required): The sandbox ID.
Request body: None
Response example:
{
"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"
}
Deleting a sandbox performs the following operations:
-
Checks if the sandbox exists.
-
If the sandbox is in the
READYstate, it first calls StopSandbox to delete the FC session. -
Returns the status of the sandbox before deletion.
Status descriptions
The status flow of a sandbox is as follows:
-
CREATING: The sandbox instance is being created. -
READY: Ready to use. -
TERMINATED: The sandbox instance has been stopped using the StopSandbox API operation.
Error responses
All API operations return errors in a unified format:
{
"error": {
"code": "ERROR_CODE",
"message": "Error description"
}
}
Common error codes:
-
400 Bad Request: The request parameters are invalid. -
404 Not Found: The sandbox does not exist. -
500 Internal Server Error: An internal server error occurred.
Health check
Check service health status
Context management
File system operations
Code execution
Terminal execution
Process management
More information
Resource management
-
Clean up resources promptly:
-
Delete unnecessary files after tasks are complete.
-
Delete unused contexts and sessions promptly.
-
Monitor storage space usage.
-
-
Set reasonable timeout periods:
-
Short-term tasks: For short-term tasks, use a shorter timeout period, such as 5 to 10 minutes.
-
Long-term tasks: For long-term tasks, use a longer timeout period, such as 30 minutes to 6 hours.
-
Code execution
-
Error handling:
import traceback
try:
# Your code
result = some_function()
print(f"Execution successful: {result}")
except Exception as e:
print(f"Execution failed: {str(e)}")
traceback.print_exc()
-
Processing large data:
-
Use libraries such as pandas to read large files in chunks.
-
Release large objects from memory promptly.
-
Use generators to process large datasets.
-
-
File operations:
import os
import pandas as pd
# Check if the file exists
if os.path.exists('/workspace/data.csv'):
df = pd.read_csv('/workspace/data.csv')
print(f"Read {len(df)} rows of data")
Security considerations
-
Input validation:
-
Validate the type and size of uploaded files.
-
Check file paths to prevent directory traversal attacks.
-
-
Access control:
-
Configure the `executionRoleArn` parameter based on the principle of least privilege.
-
Review and update credentials regularly.
-
-
Data protection:
-
Delete sensitive data promptly after it is used.
-
Avoid hard coding sensitive information in your code.
-