Dify Sandbox Python SDK
Python SDK for interacting with the Dify Sandbox API.
Installation
pip install -e sdk/
Or install dependencies directly:
pip install requests
Quick Start
from dify_sandbox import DifySandboxClient
# Initialize client
client = DifySandboxClient(
base_url="http://localhost:8194",
api_key="your-api-key"
)
# Run Python code
result = client.run_python("print('Hello from sandbox!')")
print(result.stdout) # Output: Hello from sandbox!
# Run Node.js code
result = client.run_nodejs("console.log('Hello from Node.js!')")
print(result.stdout) # Output: Hello from Node.js!
## Features
- **Code Execution**: Run Python and Node.js code in a secure sandbox
- **File Operations**: Upload, download, and delete files to/from the sandbox
- **Dependency Management**: View and manage sandbox dependencies
- **Package Installation**: Install Python packages via pip with version specifier support
- **Command Execution**: Run commands in the sandbox upload directory with security restrictions
- **Health Check**: Monitor sandbox server status
## Recent Updates
### Command & Package Installation APIs (Latest)
Added two new endpoints for package installation and command execution:
```python
# Install a Python package (supports version specifiers)
result = client.install_package("requests==2.31.0", enable_network=True)
print(result.stdout)
# Run a command in the sandbox upload directory
result = client.run_command("python3", ["script.py"], enable_network=False)
print(result.stdout)
File Deletion API
Added support for deleting files from the sandbox:
# Delete a file from sandbox
response = client.delete_file("uploaded_file.txt")
print(response.message) # Deletion result message
The default upload directory has also been updated for better file management.
API Reference
Client Initialization
client = DifySandboxClient(
base_url="http://localhost:8194", # Sandbox server URL
api_key="your-api-key", # API key for authentication
timeout=30 # Request timeout in seconds
)
Code Execution
Run Python Code
result = client.run_python(
code="print('Hello, World!')",
preload="", # Optional: code to run before main code
enable_network=False # Optional: enable network access
)
print(result.stdout) # Standard output
print(result.stderr) # Standard error
print(result.exit_code) # Exit code (0 = success)
Run Node.js Code
result = client.run_nodejs(
code="console.log('Hello, World!')",
preload="",
enable_network=False
)
print(result.stdout)
print(result.stderr)
print(result.exit_code)
File Operations
Upload File
# Upload from file path
result = client.upload_file("/path/to/file.txt")
print(result.filename) # Uploaded filename in sandbox
print(result.size) # File size in bytes
# Upload from file object
with open("local_file.txt", "rb") as f:
result = client.upload_file(f, filename="custom_name.txt")
Download File
# Download to memory
content = client.download_file("sandbox_file.txt")
# Download to local file
client.download_file("sandbox_file.txt", save_path="local_copy.txt")
Dependency Management
Get Dependencies
deps = client.get_dependencies(language="python3")
print(deps.dependencies) # List of installed packages
Update Dependencies
response = client.update_dependencies(language="python3")
print(response.message)
Refresh Dependencies
response = client.refresh_dependencies(language="python3")
print(response.message)
Package Installation
Install Python Package
Install a Python package using pip. Supports version specifiers (==, >=, ~=, etc.) and extras ([security]).
# Install latest version
result = client.install_package("requests")
print(result.stdout)
# Install specific version
result = client.install_package("requests==2.31.0", enable_network=True)
print(result.exit_code) # 0 = success
Parameters:
| Parameter | Type | Required | Description |
|---|---|---|---|
package_name |
str |
Yes | Package name with optional version specifier |
enable_network |
bool |
No | Allow network access during install (default: True) |
Security: Package names are validated to prevent command injection. Dangerous characters (;|&$\(){}) and path traversal (..`) are blocked. Git URLs and local paths are not supported.
Command Execution
Run Command
Run a command in the sandbox upload directory. The working directory is always set to upload_dir to prevent path traversal attacks.
# Run a Python script in the upload directory
result = client.run_command("python3", ["script.py"])
print(result.stdout)
# Run with network access
result = client.run_command("curl", ["-s", "https://example.com"], enable_network=True)
Parameters:
| Parameter | Type | Required | Description |
|---|---|---|---|
command |
str |
Yes | Command to execute |
args |
list |
No | Command arguments (default: []) |
enable_network |
bool |
No | Allow network access (default: False) |
Security: Dangerous commands (rm, shutdown, kill, chmod, sudo, etc.), dangerous paths (/etc, /bin, C:\Windows, etc.), and path traversal attempts are blocked.
Health Check
if client.health_check():
print("Sandbox is healthy")
else:
print("Sandbox is not responding")
Data Models
RunCodeResponse
@dataclass
class RunCodeResponse:
stdout: str # Standard output from code execution
stderr: str # Standard error from code execution
exit_code: int # Exit code (0 = success)
UploadFileResponse
@dataclass
class UploadFileResponse:
filename: str # Filename in sandbox
size: int # File size in bytes
DependencyInfo
@dataclass
class DependencyInfo:
language: str # Language (python3/nodejs)
dependencies: list # List of dependencies
InstallPackageResponse
@dataclass
class InstallPackageResponse:
stdout: str # Standard output from pip install
stderr: str # Standard error from pip install
exit_code: int # Exit code (0 = success)
RunCommandResponse
@dataclass
class RunCommandResponse:
stdout: str # Standard output from command execution
stderr: str # Standard error from command execution
exit_code: int # Exit code (0 = success)
DifySandboxResponse
@dataclass
class DifySandboxResponse:
code: int # Response code (0 = success)
message: str # Response message
data: Any # Response data
Examples
See the examples/ directory for complete usage examples:
basic_usage.py- Basic code execution examplesfile_operations.py- File upload and download examplesdependency_management.py- Dependency management examples
Error Handling
The SDK raises exceptions for API errors:
try:
result = client.run_python("invalid code")
except Exception as e:
print(f"Error: {e}")
License
MIT License
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file dify_sandbox-1.1.1.tar.gz.
File metadata
- Download URL: dify_sandbox-1.1.1.tar.gz
- Upload date:
- Size: 9.0 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via:
twine/7.0.0 CPython/3.11.9
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
e79d6d7195bf5f54eab46404c27eece09d0bfed794087bf54df8ae8e87b94046
|
|
| MD5 |
adbc580a4517e3463569fc7359e508c0
|
|
| BLAKE2b-256 |
0d9d0ff3c7ed80deed263bf0f041b0023f84d1a0455c506517c67f07efc1dde7
|
File details
Details for the file dify_sandbox-1.1.1-py3-none-any.whl.
File metadata
- Download URL: dify_sandbox-1.1.1-py3-none-any.whl
- Upload date:
- Size: 7.8 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via:
twine/7.0.0 CPython/3.11.9
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
0a6670a3793e8e958545614d4dedc2e68d735d0d15d58f59ff494f3210948b6c
|
|
| MD5 |
94abd12e5e5c0a3047d66575184dcae0
|
|
| BLAKE2b-256 |
09f64b564675a9bd9b2d81e307e9e299029bde3a53d9b778b2c3d471b1d608a9
|