Sandbox 模块¶
Sandbox模块提供了隔离环境以安全地运行代码。
公共接口¶
用户通常直接从agentscope_runtime.sandbox包导入的主要类:
BaseSandbox¶
- class agentscope_runtime.sandbox.BaseSandbox(sandbox_id=None, timeout=3000, base_url=None, bearer_token=None, sandbox_type=SandboxType.BASE)[source]
Bases:
Sandbox- Parameters:
- __init__(sandbox_id=None, timeout=3000, base_url=None, bearer_token=None, sandbox_type=SandboxType.BASE)[source]
Initialize the sandbox interface.
BrowserSandbox¶
- class agentscope_runtime.sandbox.BrowserSandbox(sandbox_id=None, timeout=3000, base_url=None, bearer_token=None, sandbox_type=SandboxType.BROWSER)[source]
Bases:
GUIMixin,BaseSandbox- Parameters:
- __init__(sandbox_id=None, timeout=3000, base_url=None, bearer_token=None, sandbox_type=SandboxType.BROWSER)[source]
- browser_close()[source]
Close the current browser page.
- browser_resize(width, height)[source]
Resize the browser window.
- browser_console_messages()[source]
Return all console messages from the browser.
- browser_handle_dialog(accept, prompt_text='')[source]
Handle a dialog popup.
- browser_file_upload(paths)[source]
Upload one or multiple files in the browser.
- browser_press_key(key)[source]
Press a key on the keyboard.
- Parameters:
key (str) – Name of the key to press or a character to enter.
- browser_navigate(url)[source]
Navigate to a specified URL.
- Parameters:
url (str) – The URL to load in the browser.
- browser_navigate_back()[source]
Go back to the previous page.
- browser_navigate_forward()[source]
Go forward to the next page.
- browser_network_requests()[source]
Return all network requests since the page was loaded.
- browser_pdf_save(filename='')[source]
Save the current page as a PDF.
- Parameters:
filename (str, optional) – File name to save the PDF as.
- browser_take_screenshot(raw=False, filename='', element='', ref='')[source]
Take a screenshot of the current page or of a specific element.
- Parameters:
- browser_snapshot()[source]
Capture an accessibility snapshot of the current page.
- browser_click(element, ref)[source]
Click on an element in the current page.
- browser_drag(start_element, start_ref, end_element, end_ref)[source]
Drag from one element and drop onto another.
- browser_hover(element, ref)[source]
Hover over an element in the current page.
- browser_type(element, ref, text, submit=False, slowly=False)[source]
Type text into an editable element.
- browser_select_option(element, ref, values)[source]
Select options in a dropdown.
- browser_tab_list()[source]
List all browser tabs.
- browser_tab_new(url='')[source]
Open a new browser tab.
- Parameters:
url (str, optional) – URL to open in the new tab. Blank if not provided.
- browser_tab_select(index)[source]
Select a browser tab by index.
- Parameters:
index (int) – Index of the tab to select.
FilesystemSandbox¶
- class agentscope_runtime.sandbox.FilesystemSandbox(sandbox_id=None, timeout=3000, base_url=None, bearer_token=None, sandbox_type=SandboxType.FILESYSTEM)[source]
Bases:
GUIMixin,BaseSandbox- Parameters:
- __init__(sandbox_id=None, timeout=3000, base_url=None, bearer_token=None, sandbox_type=SandboxType.FILESYSTEM)[source]
- read_file(path)[source]
Read the complete contents of a file.
- Parameters:
path (str) – Path to the file to read.
- read_multiple_files(paths)[source]
Read the contents of multiple files simultaneously.
- write_file(path, content)[source]
Create a new file or overwrite an existing file with new content.
- edit_file(path, edits, dry_run=False)[source]
Make line-based edits to a text file.
- create_directory(path)[source]
Create a new directory or ensure it exists.
- Parameters:
path (str) – Path to the directory to create.
- list_directory(path)[source]
Get a detailed listing of all files and directories in a specified path.
- Parameters:
path (str) – Path to list contents from.
- directory_tree(path)[source]
Get a recursive tree view of files and directories as a JSON structure.
- Parameters:
path (str) – Path to get tree structure from.
- move_file(source, destination)[source]
Move or rename files and directories.
- search_files(path, pattern, exclude_patterns=[])[source]
Recursively search for files and directories matching a pattern.
- get_file_info(path)[source]
Retrieve detailed metadata about a file or directory.
- Parameters:
path (str) – Path to the file or directory.
- list_allowed_directories()[source]
Returns the list of directories that this serveris allowed to access.
GuiSandbox¶
- class agentscope_runtime.sandbox.GuiSandbox(sandbox_id=None, timeout=3000, base_url=None, bearer_token=None, sandbox_type=SandboxType.GUI)[source]
Bases:
GUIMixin,BaseSandbox- Parameters:
- __init__(sandbox_id=None, timeout=3000, base_url=None, bearer_token=None, sandbox_type=SandboxType.GUI)[source]
- computer_use(action, coordinate=None, text=None)[source]
Use a mouse and keyboard to interact with a computer, and take screenshots.
This is an interface to a desktop GUI. You do not have access to a terminal or applications menu. You must click on desktop icons to start applications.
- Guidelines:
Always prefer using keyboard shortcuts rather than clicking, where possible.
If you see boxes with two letters in them, typing these letters will click that element. Use this instead of other shortcuts or clicking, where possible.
Some applications may take time to start or process actions, so you may need to wait and take successive screenshots to see the results of your actions. For example, if you click on Firefox and a window doesn’t open, try taking another screenshot.
Whenever you intend to move the cursor to click on an element (like an icon), consult a screenshot to determine the coordinates of the element before moving the cursor.
If clicking on a program or link fails to load, even after waiting, try adjusting your cursor position so that the tip falls visually on the element you want to click.
Make sure to click any buttons, links, icons, etc., with the cursor tip in the center of the element. Don’t click boxes on their edges unless asked.
- Parameters:
action (str) – The action to perform. Options are: * key: Press a key or key-combination on the keyboard. * type: Type a string of text. * get_cursor_position: Get the current (x, y) pixel coordinate of the cursor. * mouse_move: Move the cursor to a specified (x, y) coordinate. * left_click: Click the left mouse button. * left_click_drag: Click and drag to a specified coordinate. * right_click: Click the right mouse button. * middle_click: Click the middle mouse button. * double_click: Double-click the left mouse button. * get_screenshot: Take a screenshot of the screen.
coordinate (list[float] | tuple[float, float], optional) – The (x, y) pixel coordinates. x = pixels from the left edge, y = pixels from the top edge.
text (str, optional) – Text to type or key command to execute.
- Returns:
Result of performing the specified computer action.
- Return type:
Any
MobileSandbox¶
- class agentscope_runtime.sandbox.MobileSandbox(sandbox_id=None, timeout=3000, base_url=None, bearer_token=None, sandbox_type=SandboxType.MOBILE)[source]
Bases:
Sandbox- Parameters:
- __init__(sandbox_id=None, timeout=3000, base_url=None, bearer_token=None, sandbox_type=SandboxType.MOBILE)[source]
Initialize the sandbox interface.
- adb_use(action, coordinate=None, start=None, end=None, duration=None, code=None, text=None)[source]
A general-purpose method to execute various ADB actions.
This function acts as a low-level dispatcher for different ADB commands. Only the parameters relevant to the specified action should be provided. For actions involving coordinates, the values are absolute pixels, with the origin (0, 0) at the top-left of the screen.
- Parameters:
action (str) – The specific ADB action to perform. Examples: ‘tap’, ‘swipe’, ‘input_text’, ‘key_event’, ‘get_screenshot’, ‘get_screen_resolution’.
coordinate (Optional[List[int]]) – The [x, y] coordinates for a ‘tap’ action.
start (Optional[List[int]]) – The starting [x, y] coordinates for a ‘swipe’ action.
end (Optional[List[int]]) – The ending [x, y] coordinates for a ‘swipe’ action.
duration (int, optional) – The duration of a ‘swipe’ gesture in milliseconds.
code (int | str, optional) – The key event code (e.g., 3) or name (e.g., ‘HOME’) for the ‘key_event’ action.
text (Optional[str]) – The text string to be entered for the ‘input_text’ action.
- mobile_get_screen_resolution()[source]
Get the screen resolution of the connected mobile device.
- mobile_tap(x, y)[source]
Tap a specific coordinate on the screen.
- mobile_swipe(start, end, duration=None)[source]
Perform a swipe gesture on the screen from a start point to an end point.
- mobile_input_text(text)[source]
Input a text string into the currently focused UI element.
- Parameters:
text (str) – The string to be inputted.
- mobile_key_event(code)[source]
Send an Android key event to the device.
- mobile_get_screenshot()[source]
Take a screenshot of the current device screen.
TrainingSandbox¶
- class agentscope_runtime.sandbox.TrainingSandbox(sandbox_id=None, timeout=3000, base_url=None, bearer_token=None, box_type=SandboxType.APPWORLD)[source]
Bases:
SandboxTraining Sandbox class for managing and executing training-related tasks.
This class provides methods to create, manage, and interact with training environment instances using specialized tool calls.
- Parameters:
- __init__(sandbox_id=None, timeout=3000, base_url=None, bearer_token=None, box_type=SandboxType.APPWORLD)[source]
Initialize the Training Sandbox.
- create_instance(env_type, task_id, instance_id=None, params=None)[source]
Create a new instance of a training environment.
- get_task_ids(env_type, split='train', params=None)[source]
Retrieve task identifiers for a specific environment.
- get_env_profile(env_type, split='train', params=None)[source]
Retrieve the environment profile.
- step(instance_id, action=None, params=None)[source]
Execute a step in the training environment.
- evaluate(instance_id, messages=None, params=None)[source]
Evaluate the performance of a training environment instance.
- Parameters:
instance_id (str) – Identifier of the environment instance.
messages (Dict, optional) – Evaluation-related messages.
params (Dict, optional) – Additional evaluation parameters.
- Returns:
Evaluation results.
CloudSandbox¶
- class agentscope_runtime.sandbox.CloudSandbox(sandbox_id=None, timeout=3000, base_url=None, bearer_token=None, sandbox_type=SandboxType.AGENTBAY, **kwargs)[source]
Bases:
Sandbox,ABCBase class for cloud-based sandbox implementations.
This class provides a unified interface for cloud sandbox services that don’t depend on local container management. Instead, they communicate directly with cloud APIs to manage remote environments.
Key features: - No local container dependency - Direct cloud API communication - Unified interface for cloud sandbox operations - Support for different cloud providers
- Parameters:
- __init__(sandbox_id=None, timeout=3000, base_url=None, bearer_token=None, sandbox_type=SandboxType.AGENTBAY, **kwargs)[source]
Initialize the cloud sandbox.
- Parameters:
sandbox_id (str | None) – Optional sandbox ID for existing sessions
timeout (int) – Timeout for operations in seconds
base_url (str | None) – Base URL for cloud API (optional, may use default)
bearer_token (str | None) – Authentication token for cloud API
sandbox_type (SandboxType) – Type of sandbox (default: AGENTBAY)
**kwargs – Additional cloud-specific configuration
- call_tool(name, arguments=None)[source]
Call a tool in the cloud sandbox.
- get_info()[source]
Get information about the cloud sandbox.
- list_tools(tool_type=None)[source]
List available tools in the cloud sandbox.
- add_mcp_servers(server_configs, overwrite=False)[source]
Add MCP servers to the cloud sandbox.
- __enter__()[source]
Context manager entry.
- __exit__(exc_type, exc_value, traceback)[source]
Context manager exit with cleanup.
AgentbaySandbox¶
- class agentscope_runtime.sandbox.AgentbaySandbox(sandbox_id=None, timeout=3000, base_url=None, bearer_token=None, sandbox_type=SandboxType.AGENTBAY, api_key=None, image_id='linux_latest', labels=None, **kwargs)[source]
Bases:
CloudSandboxAgentBay cloud sandbox implementation.
This sandbox provides access to AgentBay’s cloud-native sandbox environment with support for various image types including Linux, Windows, Browser, CodeSpace, and Mobile environments.
Features: - Cloud-native environment (no local containers) - Support for multiple image types - Direct API communication with AgentBay - Session management and lifecycle control - Tool execution in cloud environment
- Parameters:
- __init__(sandbox_id=None, timeout=3000, base_url=None, bearer_token=None, sandbox_type=SandboxType.AGENTBAY, api_key=None, image_id='linux_latest', labels=None, **kwargs)[source]
Initialize the AgentBay sandbox.
- Parameters:
sandbox_id (str | None) – Optional sandbox ID for existing sessions
timeout (int) – Timeout for operations in seconds
base_url (str | None) – Base URL for AgentBay API (optional)
bearer_token (str | None) – Authentication token (deprecated, use api_key)
sandbox_type (SandboxType) – Type of sandbox (default: AGENTBAY)
api_key (str | None) – AgentBay API key (from environment or parameter)
image_id (str) – AgentBay image type (linux_latest, windows_latest, etc.)
labels (Dict[str, str] | None) – Optional labels for session organization
**kwargs – Additional configuration
- list_tools(tool_type=None)[source]
List available tools in the AgentBay sandbox.
- get_session_info()[source]
Get detailed information about the AgentBay session.
自定义与示例¶
- class agentscope_runtime.sandbox.custom.custom_sandbox.CustomSandbox(sandbox_id=None, timeout=3000, base_url=None, bearer_token=None)[source]
Bases:
Sandbox
- class agentscope_runtime.sandbox.custom.example.ExampleSandbox(sandbox_id=None, timeout=3000, base_url=None, bearer_token=None)[source]
Bases:
Sandbox
管理端¶
- agentscope_runtime.sandbox.manager.sandbox_manager.remote_wrapper(method='POST', success_key='data')[source]
Decorator to handle both remote and local method execution.
- class agentscope_runtime.sandbox.manager.sandbox_manager.SandboxManager(config=None, base_url=None, bearer_token=None, default_type=SandboxType.BASE)[source]
Bases:
object- Parameters:
- __init__(config=None, base_url=None, bearer_token=None, default_type=SandboxType.BASE)[source]
- cleanup()[source]
- create_from_pool(sandbox_type=None, meta=None)[source]
Try to get a container from runtime pool
- Parameters:
meta (Dict | None)
- create(sandbox_type=None, mount_dir=None, storage_path=None, environment=None, meta=None)[source]
- release(identity)[source]
- start(identity)[source]
- stop(identity)[source]
- get_status(identity)[source]
Get container status by container_name or container_id.
- get_info(identity)[source]
Get container information by container_name or container_id.
- check_health(identity)[source]
List tool
- list_tools(identity, tool_type=None, **kwargs)[source]
List tool
- call_tool(identity, tool_name=None, arguments=None)[source]
Call tool
- add_mcp_servers(identity, server_configs, overwrite=False)[source]
Add MCP servers to runtime.
- get_session_mapping(session_ctx_id)[source]
Get all container names bound to a session context
- agentscope_runtime.sandbox.manager.server.app.get_config()[source]
Return config
- Return type:
SandboxManagerEnvConfig
- agentscope_runtime.sandbox.manager.server.app.verify_token(credentials=Depends(dependency=<fastapi.security.http.HTTPBearer object>, use_cache=True, scope=None))[source]
Verify Bearer token
- Parameters:
credentials (HTTPAuthorizationCredentials)
- agentscope_runtime.sandbox.manager.server.app.get_sandbox_manager()[source]
Get or create the global SandboxManager instance
- agentscope_runtime.sandbox.manager.server.app.create_endpoint(method)[source]
- agentscope_runtime.sandbox.manager.server.app.register_routes(_app, instance)[source]
- async agentscope_runtime.sandbox.manager.server.app.startup_event()[source]
Initialize the SandboxManager on startup
- async agentscope_runtime.sandbox.manager.server.app.shutdown_event()[source]
Cleanup resources on shutdown
- async agentscope_runtime.sandbox.manager.server.app.health_check()[source]
Health check endpoint
- async agentscope_runtime.sandbox.manager.server.app.proxy_vnc_static(sandbox_id, path)[source]
- async agentscope_runtime.sandbox.manager.server.app.websocket_endpoint(websocket, sandbox_id)[source]
- Parameters:
websocket (WebSocket)
sandbox_id (str)
- agentscope_runtime.sandbox.manager.server.app.setup_logging(log_level)[source]
Setup logging configuration based on log level
- Parameters:
log_level (str)
- agentscope_runtime.sandbox.manager.server.app.main()[source]
Main entry point for the Runtime Manager Service
- class agentscope_runtime.sandbox.manager.server.config.Settings(_case_sensitive=None, _nested_model_default_partial_update=None, _env_prefix=None, _env_file=PosixPath('.'), _env_file_encoding=None, _env_ignore_empty=None, _env_nested_delimiter=None, _env_nested_max_split=None, _env_parse_none_str=None, _env_parse_enums=None, _cli_prog_name=None, _cli_parse_args=None, _cli_settings_source=None, _cli_parse_none_str=None, _cli_hide_none_type=None, _cli_avoid_json=None, _cli_enforce_required=None, _cli_use_class_docs_for_groups=None, _cli_exit_on_error=None, _cli_prefix=None, _cli_flag_prefix_char=None, _cli_implicit_flags=None, _cli_ignore_unknown_args=None, _cli_kebab_case=None, _cli_shortcuts=None, _secrets_dir=None, *, HOST='127.0.0.1', PORT=8000, WORKERS=1, DEBUG=False, BEARER_TOKEN=None, DEFAULT_SANDBOX_TYPE='base', POOL_SIZE=1, AUTO_CLEANUP=True, CONTAINER_PREFIX_KEY='runtime_sandbox_container_', CONTAINER_DEPLOYMENT='docker', DEFAULT_MOUNT_DIR='sessions_mount_dir', READONLY_MOUNTS=None, STORAGE_FOLDER='runtime_sandbox_storage', PORT_RANGE=(49152, 59152), REDIS_ENABLED=False, REDIS_SERVER='localhost', REDIS_PORT=6379, REDIS_DB=0, REDIS_USER=None, REDIS_PASSWORD=None, REDIS_PORT_KEY='_runtime_sandbox_container_occupied_ports', REDIS_CONTAINER_POOL_KEY='_runtime_sandbox_container_container_pool', FILE_SYSTEM='local', OSS_ENDPOINT='http://oss-cn-hangzhou.aliyuncs.com', OSS_ACCESS_KEY_ID='your-access-key-id', OSS_ACCESS_KEY_SECRET='your-access-key-secret', OSS_BUCKET_NAME='your-bucket-name', K8S_NAMESPACE='default', KUBECONFIG_PATH=None, AGENT_RUN_ACCOUNT_ID=None, AGENT_RUN_ACCESS_KEY_ID=None, AGENT_RUN_ACCESS_KEY_SECRET=None, AGENT_RUN_REGION_ID='cn-hangzhou', AGENT_RUN_CPU=2.0, AGENT_RUN_MEMORY=2048, AGENT_RUN_VPC_ID=None, AGENT_RUN_VSWITCH_IDS=None, AGENT_RUN_SECURITY_GROUP_ID=None, AGENT_RUN_PREFIX='agentscope-sandbox', AGENT_RUN_LOG_PROJECT=None, AGENT_RUN_LOG_STORE=None, FC_ACCOUNT_ID=None, FC_ACCESS_KEY_ID=None, FC_ACCESS_KEY_SECRET=None, FC_REGION_ID='cn-hangzhou', FC_CPU=2.0, FC_MEMORY=2048, FC_VPC_ID=None, FC_VSWITCH_IDS=None, FC_SECURITY_GROUP_ID=None, FC_PREFIX='agentscope-sandbox', FC_LOG_PROJECT=None, FC_LOG_STORE=None, **values)[source]
Bases:
BaseSettingsRuntime Manager Service Settings
- Parameters:
_case_sensitive (bool | None)
_nested_model_default_partial_update (bool | None)
_env_prefix (str | None)
_env_file (DotenvType | None)
_env_file_encoding (str | None)
_env_ignore_empty (bool | None)
_env_nested_delimiter (str | None)
_env_nested_max_split (int | None)
_env_parse_none_str (str | None)
_env_parse_enums (bool | None)
_cli_prog_name (str | None)
_cli_settings_source (CliSettingsSource[Any] | None)
_cli_parse_none_str (str | None)
_cli_hide_none_type (bool | None)
_cli_avoid_json (bool | None)
_cli_enforce_required (bool | None)
_cli_use_class_docs_for_groups (bool | None)
_cli_exit_on_error (bool | None)
_cli_prefix (str | None)
_cli_flag_prefix_char (str | None)
_cli_implicit_flags (bool | None)
_cli_ignore_unknown_args (bool | None)
_cli_kebab_case (bool | Literal['all', 'no_enums'] | None)
_secrets_dir (PathType | None)
HOST (str)
PORT (int)
WORKERS (int)
DEBUG (bool)
BEARER_TOKEN (str | None)
POOL_SIZE (int)
AUTO_CLEANUP (bool)
CONTAINER_PREFIX_KEY (str)
CONTAINER_DEPLOYMENT (Literal['docker', 'cloud', 'k8s', 'agentrun', 'fc'])
DEFAULT_MOUNT_DIR (str)
STORAGE_FOLDER (str)
REDIS_ENABLED (bool)
REDIS_SERVER (str)
REDIS_PORT (int)
REDIS_DB (int)
REDIS_USER (str | None)
REDIS_PASSWORD (str | None)
REDIS_PORT_KEY (str)
REDIS_CONTAINER_POOL_KEY (str)
FILE_SYSTEM (Literal['local', 'oss'])
OSS_ENDPOINT (str)
OSS_ACCESS_KEY_ID (str)
OSS_ACCESS_KEY_SECRET (str)
OSS_BUCKET_NAME (str)
K8S_NAMESPACE (str)
KUBECONFIG_PATH (str | None)
AGENT_RUN_ACCOUNT_ID (str | None)
AGENT_RUN_ACCESS_KEY_ID (str | None)
AGENT_RUN_ACCESS_KEY_SECRET (str | None)
AGENT_RUN_REGION_ID (str)
AGENT_RUN_CPU (float)
AGENT_RUN_MEMORY (int)
AGENT_RUN_VPC_ID (str | None)
AGENT_RUN_SECURITY_GROUP_ID (str | None)
AGENT_RUN_PREFIX (str)
AGENT_RUN_LOG_PROJECT (str | None)
AGENT_RUN_LOG_STORE (str | None)
FC_ACCOUNT_ID (str | None)
FC_ACCESS_KEY_ID (str | None)
FC_ACCESS_KEY_SECRET (str | None)
FC_REGION_ID (str)
FC_CPU (float)
FC_MEMORY (int)
FC_VPC_ID (str | None)
FC_SECURITY_GROUP_ID (str | None)
FC_PREFIX (str)
FC_LOG_PROJECT (str | None)
FC_LOG_STORE (str | None)
values (Any)
- HOST: str
- PORT: int
- WORKERS: int
- DEBUG: bool
- POOL_SIZE: int
- AUTO_CLEANUP: bool
- CONTAINER_PREFIX_KEY: str
- CONTAINER_DEPLOYMENT: Literal['docker', 'cloud', 'k8s', 'agentrun', 'fc']
- DEFAULT_MOUNT_DIR: str
- STORAGE_FOLDER: str
- REDIS_ENABLED: bool
- REDIS_SERVER: str
- REDIS_PORT: int
- REDIS_DB: int
- REDIS_PORT_KEY: str
- REDIS_CONTAINER_POOL_KEY: str
- FILE_SYSTEM: Literal['local', 'oss']
- OSS_ENDPOINT: str
- OSS_ACCESS_KEY_ID: str
- OSS_ACCESS_KEY_SECRET: str
- OSS_BUCKET_NAME: str
- K8S_NAMESPACE: str
- AGENT_RUN_REGION_ID: str
- AGENT_RUN_CPU: float
- AGENT_RUN_MEMORY: int
- AGENT_RUN_PREFIX: str
- FC_REGION_ID: str
- FC_CPU: float
- FC_MEMORY: int
- FC_PREFIX: str
- model_config: ClassVar[SettingsConfigDict] = {'arbitrary_types_allowed': True, 'case_sensitive': True, 'cli_avoid_json': False, 'cli_enforce_required': False, 'cli_exit_on_error': True, 'cli_flag_prefix_char': '-', 'cli_hide_none_type': False, 'cli_ignore_unknown_args': False, 'cli_implicit_flags': False, 'cli_kebab_case': False, 'cli_parse_args': None, 'cli_parse_none_str': None, 'cli_prefix': '', 'cli_prog_name': None, 'cli_shortcuts': None, 'cli_use_class_docs_for_groups': False, 'enable_decoding': True, 'env_file': None, 'env_file_encoding': None, 'env_ignore_empty': False, 'env_nested_delimiter': None, 'env_nested_max_split': None, 'env_parse_enums': None, 'env_parse_none_str': None, 'env_prefix': '', 'extra': 'allow', 'json_file': None, 'json_file_encoding': None, 'nested_model_default_partial_update': False, 'protected_namespaces': ('model_validate', 'model_dump', 'settings_customise_sources'), 'secrets_dir': None, 'toml_file': None, 'validate_default': True, 'yaml_config_section': None, 'yaml_file': None, 'yaml_file_encoding': None}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- classmethod validate_workers(value, info)[source]
- classmethod parse_default_type(v)[source]
- agentscope_runtime.sandbox.manager.server.config.get_settings(config_file=None)[source]
- Parameters:
config_file (str | None)
- Return type:
Settings
- class agentscope_runtime.sandbox.manager.server.models.ErrorResponse(*, error, detail=None)[source]
Bases:
BaseModelError response model
- error: str
- model_config: ClassVar[ConfigDict] = {}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class agentscope_runtime.sandbox.manager.server.models.HealthResponse(*, status, version)[source]
Bases:
BaseModelHealth check response model
- status: str
- version: str
- model_config: ClassVar[ConfigDict] = {}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class agentscope_runtime.sandbox.manager.storage.data_storage.DataStorage[source]
Bases:
ABC- abstract download_folder(source_path, destination_path)[source]
Download a folder from storage to a local path.
- abstract upload_folder(source_path, destination_path)[source]
Upload a local folder to storage.
- abstract path_join(*args)[source]
Joins multiple path components into a single path string.
- class agentscope_runtime.sandbox.manager.storage.local_storage.LocalStorage[source]
Bases:
DataStorage- download_folder(source_path, destination_path)[source]
Copy a folder from source_path to destination_path.
- upload_folder(source_path, destination_path)[source]
Copy a folder from source_path to destination_path.
- path_join(*args)[source]
Join path components.
- agentscope_runtime.sandbox.manager.storage.oss_storage.calculate_md5(file_path)[source]
Calculate the MD5 checksum of a file.
- class agentscope_runtime.sandbox.manager.storage.oss_storage.OSSStorage(access_key_id, access_key_secret, endpoint, bucket_name)[source]
Bases:
DataStorage- __init__(access_key_id, access_key_secret, endpoint, bucket_name)[source]
- download_folder(source_path, destination_path)[source]
Download a folder from OSS to the local filesystem.
- upload_folder(source_path, destination_path)[source]
Upload a local folder to OSS.
- path_join(*args)[source]
Join path components for OSS.
客户端¶
- class agentscope_runtime.sandbox.client.http_client.SandboxHttpClient(model=None, timeout=60, domain='localhost')[source]
Bases:
objectA Python client for interacting with the runtime API. Connect with container directly.
- __init__(model=None, timeout=60, domain='localhost')[source]
Initialize the Python client.
- check_health()[source]
Checks if the runtime service is running by verifying the health endpoint.
- Returns:
True if the service is reachable, False otherwise
- Return type:
- wait_until_healthy()[source]
Waits until the runtime service is running for a specified timeout.
- Return type:
None
- add_mcp_servers(server_configs, overwrite=False)[source]
Add MCP servers to runtime.
- call_tool(name, arguments=None)[source]
- run_ipython_cell(code=FieldInfo(annotation=NoneType, required=True, description='IPython code to execute'))[source]
Run an IPython cell.
- run_shell_command(command=FieldInfo(annotation=NoneType, required=True, description='Shell command to execute'))[source]
Run a shell command.
- property generic_tools: dict
- commit_changes(commit_message='Automated commit')[source]
Commit the uncommitted changes with a given commit message.
- generate_diff(commit_a=None, commit_b=None)[source]
Generate the diff between two commits or between uncommitted changes and the latest commit.
- get_workspace_file(file_path)[source]
Retrieve a file from the /workspace directory.
- create_or_edit_workspace_file(file_path, content)[source]
Create or edit a file within the /workspace directory.
- list_workspace_directories(directory='/workspace')[source]
List files in the specified directory within the /workspace.
- create_workspace_directory(directory_path)[source]
Create a directory within the /workspace directory.
- delete_workspace_file(file_path)[source]
Delete a file within the /workspace directory.
- delete_workspace_directory(directory_path, recursive=False)[source]
Delete a directory within the /workspace directory.
- move_or_rename_workspace_item(source_path, destination_path)[source]
Move or rename a file or directory within the /workspace directory.
Module for the training sandbox client.
- class agentscope_runtime.sandbox.client.training_client.TrainingSandboxClient(base_url='http://localhost:8000')[source]
Bases:
objectClient for interacting with the training sandbox.
- Parameters:
base_url (str)
- wait_until_healthy()[source]
Waits until the runtime service is running for a specified timeout.
- Return type:
None
- check_health()[source]
Checks if the runtime service is running by verifying the health endpoint.
- Returns:
True if the service is reachable, False otherwise
- Return type:
- get_task_ids(env_type, split='train', params=None)[source]
Get task id list
- get_env_profile(env_type, split='train', params=None)[source]
get environment profile
- get_tools_info(instance_id, messages=None, params=None)[source]
get tools information
- create_instance(env_type, task_id, instance_id=None, params=None)[source]
create instance of a task
- step(instance_id, action=None, params=None)[source]
execute step transmission
- evaluate(instance_id, messages=None, params=None)[source]
evaluate instance execution
- release_instance(instance_id)[source]
release instance from memory
- add_mcp_servers(server_configs, overwrite=False)[source]
add mcp for future
- list_tools(**kwargs)[source]
list tools
模型与注册¶
- class agentscope_runtime.sandbox.model.api.RuntimeDiffResult(*, diff=None, url=None)[source]
Bases:
BaseModel- model_config: ClassVar[ConfigDict] = {}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class agentscope_runtime.sandbox.model.container.ContainerModel(*, session_id, container_id, container_name, url, ports, mount_dir=None, storage_path=None, runtime_token=None, version=None, meta=<factory>, timeout=None, **extra_data)[source]
Bases:
BaseModel- Parameters:
- session_id: str
- container_id: str
- container_name: str
- url: str
- model_config: ClassVar[ConfigDict] = {'extra': 'allow'}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class agentscope_runtime.sandbox.model.manager_config.SandboxManagerEnvConfig(*, container_prefix_key='runtime_sandbox_container_', file_system, storage_folder='', redis_enabled, container_deployment, default_mount_dir=None, readonly_mounts=None, port_range=(49152, 59152), pool_size=0, oss_endpoint='http://oss-cn-hangzhou.aliyuncs.com', oss_access_key_id=None, oss_access_key_secret=None, oss_bucket_name=None, redis_server='localhost', redis_port=6379, redis_db=0, redis_user=None, redis_password=None, redis_port_key='_runtime_sandbox_container_occupied_ports', redis_container_pool_key='_runtime_sandbox_container_container_pool', k8s_namespace='default', kubeconfig_path=None, agent_run_access_key_id=None, agent_run_access_key_secret=None, agent_run_account_id=None, agent_run_region_id='cn-hangzhou', agent_run_cpu=2, agent_run_memory=2048, agent_run_vpc_id=None, agent_run_vswitch_ids=None, agent_run_security_group_id=None, agent_run_prefix='agentscope-sandbox_', agentrun_log_project=None, agentrun_log_store=None, fc_access_key_id=None, fc_access_key_secret=None, fc_account_id=None, fc_region_id='cn-hangzhou', fc_cpu=2.0, fc_memory=2048, fc_vpc_id=None, fc_vswitch_ids=None, fc_security_group_id=None, fc_prefix='agentscope-sandbox_', fc_log_project=None, fc_log_store=None)[source]
Bases:
BaseModel- Parameters:
container_prefix_key (Annotated[str, MaxLen(max_length=38)])
file_system (Literal['local', 'oss'])
storage_folder (str | None)
redis_enabled (bool)
container_deployment (Literal['docker', 'cloud', 'k8s', 'agentrun', 'fc'])
default_mount_dir (str | None)
pool_size (int)
oss_endpoint (str | None)
oss_access_key_id (str | None)
oss_access_key_secret (str | None)
oss_bucket_name (str | None)
redis_server (str | None)
redis_port (int | None)
redis_db (int | None)
redis_user (str | None)
redis_password (str | None)
redis_port_key (str)
redis_container_pool_key (str)
k8s_namespace (str | None)
kubeconfig_path (str | None)
agent_run_access_key_id (str | None)
agent_run_access_key_secret (str | None)
agent_run_account_id (str | None)
agent_run_region_id (str)
agent_run_cpu (float)
agent_run_memory (int)
agent_run_vpc_id (str | None)
agent_run_security_group_id (str | None)
agent_run_prefix (str)
agentrun_log_project (str | None)
agentrun_log_store (str | None)
fc_access_key_id (str | None)
fc_access_key_secret (str | None)
fc_account_id (str | None)
fc_region_id (str)
fc_cpu (float)
fc_memory (int)
fc_vpc_id (str | None)
fc_security_group_id (str | None)
fc_prefix (str)
fc_log_project (str | None)
fc_log_store (str | None)
- container_prefix_key: str
- file_system: Literal['local', 'oss']
- redis_enabled: bool
- container_deployment: Literal['docker', 'cloud', 'k8s', 'agentrun', 'fc']
- pool_size: int
- redis_port_key: str
- redis_container_pool_key: str
- agent_run_region_id: str
- agent_run_cpu: float
- agent_run_memory: int
- agent_run_prefix: str
- fc_region_id: str
- fc_cpu: float
- fc_memory: int
- fc_prefix: str
- check_settings()[source]
- model_config: ClassVar[ConfigDict] = {}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class agentscope_runtime.sandbox.registry.SandboxConfig(image_name, sandbox_type, resource_limits=None, security_level='medium', timeout=60, description='', environment=None, runtime_config=None)[source]
Bases:
objectsandbox configuration information
- Parameters:
- image_name: str
- sandbox_type: SandboxType | str
- security_level: str = 'medium'
- timeout: int = 60
- description: str = ''
- __init__(image_name, sandbox_type, resource_limits=None, security_level='medium', timeout=60, description='', environment=None, runtime_config=None)
- class agentscope_runtime.sandbox.registry.SandboxRegistry[source]
Bases:
objectDocker image registry for sandboxes
- classmethod register(image_name, sandbox_type, resource_limits=None, security_level='medium', timeout=60, description='', environment=None, runtime_config=None)[source]
Decorator to register sandbox classes
- Parameters:
image_name (str) – Docker image name
sandbox_type (SandboxType | str) – Sandbox type
resource_limits (Dict | None) – Resource limit configuration
security_level (str) – Security level (low/medium/high)
timeout (int) – Timeout in seconds
description (str) – Description
environment (Dict | None) – Environment variables
runtime_config (Dict | None) – runtime configurations
- classmethod get_config(target_class)[source]
Get the sandbox configuration for a class
- Parameters:
target_class (Type)
- Return type:
SandboxConfig | None
- classmethod get_image(target_class)[source]
Get the Docker image name for a class
- classmethod get_classes_by_type(sandbox_type)[source]
Get all related classes by sandbox type
- Parameters:
sandbox_type (SandboxType | str)
- classmethod list_all_sandboxes()[source]
List all registered sandboxes
构建与工具¶
- agentscope_runtime.sandbox.build.find_free_port(start_port, end_port)[source]
- agentscope_runtime.sandbox.build.check_health(url, secret_token, timeout=120, interval=5)[source]
- agentscope_runtime.sandbox.build.build_image(build_type, dockerfile_path=None, platform_choice='linux/amd64')[source]
- agentscope_runtime.sandbox.build.main()[source]
- agentscope_runtime.sandbox.utils.build_image_uri(image_name, tag=None, registry=None, namespace=None)[source]
Build a fully qualified Docker image URI.
- Parameters:
image_name (str) – Name of the Docker image without registry/namespace. Example: “runtime-sandbox-base”.
tag (str, optional) – Base image tag. Defaults to the global
IMAGE_TAGif not provided.registry (str, optional) – Docker registry address. Defaults to the global
REGISTRY. If empty or whitespace, registry prefix will be omitted.namespace (str, optional) – Docker image namespace. Defaults to the global
IMAGE_NAMESPACE.
- Returns:
Fully qualified Docker image URI in the form:
<registry>/<namespace>/<image_name>:<tag>or<namespace>/<image_name>:<tag>if registry is omitted.- Return type:
Examples
>>> build_image_uri("runtime-sandbox-base") 'agentscope-registry.ap-southeast-1.cr.aliyuncs.com/agentscope/runtime-sandbox-base:latest'
>>> build_image_uri("runtime-sandbox-base", tag="v1.2.3") 'agentscope-registry.ap-southeast-1.cr.aliyuncs.com/agentscope/runtime-sandbox-base:v1.2.3'
>>> build_image_uri("runtime-sandbox-base", registry="") 'agentscope/runtime-sandbox-base:latest'
- agentscope_runtime.sandbox.utils.dynamic_import(ext)[source]
Dynamically import a Python file or module.
- agentscope_runtime.sandbox.utils.http_to_ws(url, use_localhost=True)[source]
- agentscope_runtime.sandbox.utils.get_platform()[source]
- class agentscope_runtime.sandbox.enums.DynamicEnumMeta(cls, bases, classdict, **kwds)[source]
Bases:
EnumMeta
- class agentscope_runtime.sandbox.enums.DynamicEnum(value)[source]
Bases:
EnumAn enumeration.
- __init__(value)[source]
- classmethod get_builtin_members()[source]
- classmethod get_dynamic_members()[source]
- is_builtin()[source]
- class agentscope_runtime.sandbox.enums.SandboxType(value)[source]
Bases:
DynamicEnumSandbox type enumeration
- DUMMY = 'dummy'
- BASE = 'base'
- BROWSER = 'browser'
- FILESYSTEM = 'filesystem'
- GUI = 'gui'
- MOBILE = 'mobile'
- APPWORLD = 'appworld'
- BFCL = 'bfcl'
- AGENTBAY = 'agentbay'
- agentscope_runtime.sandbox.mcp_server.json_type_to_python_type(json_type)[source]
Convert JSON schema type to Python type annotation.
- Parameters:
json_type (str)
- agentscope_runtime.sandbox.mcp_server.extract_content_from_mcp_response(response)[source]
Extract actual content from MCP protocol response.
- agentscope_runtime.sandbox.mcp_server.create_dynamic_function(schema, method_name, box)[source]
Safely create a function with dynamic signature using inspect API.
- agentscope_runtime.sandbox.mcp_server.register_tools(box)[source]
Register all tools with the MCP server using FastMCP decorators.
- agentscope_runtime.sandbox.mcp_server.main()[source]