### Install Dependencies with uv Source: https://github.com/shkarupa-alex/deepagents-opensandbox/blob/master/README.md Installs project dependencies using the `uv` package manager. This command ensures all necessary libraries are available for development and testing. ```bash uv sync ``` -------------------------------- ### OpensandboxProvider Configuration and Usage Source: https://context7.com/shkarupa-alex/deepagents-opensandbox/llms.txt Demonstrates how to configure and use the OpensandboxProvider for executing commands within a sandbox environment. Includes both direct configuration and environment variable-based setup. ```APIDOC ## OpensandboxProvider Configuration and Usage ### Description This section illustrates how to initialize and utilize the `OpensandboxProvider` to manage sandboxed environments. It covers direct instantiation with parameters and configuration via environment variables, along with basic sandbox operations like creation, command execution, and deletion. ### Method - **Instantiation**: `OpensandboxProvider(...)` or `OpensandboxProvider()` - **Sandbox Management**: `get_or_create()`, `execute()`, `delete()` ### Parameters (Instantiation) #### Direct Configuration - **domain** (string) - Optional - The domain and port of the OpenSandbox server. Defaults to `localhost:8080`. - **use_server_proxy** (boolean) - Optional - If `True`, all requests are routed through the OpenSandbox server. Defaults to `False`. - **api_key** (string) - Optional - API key for authentication. If not provided, it attempts to read from the `OPEN_SANDBOX_API_KEY` environment variable. #### Environment Variables - **OPEN_SANDBOX_API_KEY** (string) - API key for authentication. - **OPEN_SANDBOX_DOMAIN** (string) - OpenSandbox server domain and port. Defaults to `localhost:8080`. ### Request Example (Direct Configuration) ```python from deepagents_opensandbox import OpensandboxProvider # Server proxy mode - all requests routed through OpenSandbox server # Use when: server in Docker, client on host machine provider_proxy = OpensandboxProvider( domain="localhost:8090", use_server_proxy=True ) sandbox = provider_proxy.get_or_create(image="python:3.11") result = sandbox.execute("hostname") print(result.output) provider_proxy.delete(sandbox_id=sandbox.id) ``` ### Request Example (Environment Variables) ```python import os from deepagents_opensandbox import OpensandboxProvider # Set environment variables os.environ["OPEN_SANDBOX_API_KEY"] = "your-secret-api-key" os.environ["OPEN_SANDBOX_DOMAIN"] = "sandbox.example.com:8080" # Provider reads from environment automatically provider = OpensandboxProvider() sandbox = provider.get_or_create(image="ubuntu:22.04") result = sandbox.execute("uname -a") print(result.output) provider.delete(sandbox_id=sandbox.id) ``` ### Response (Execute Command) #### Success Response (200) - **output** (string) - The standard output of the executed command. - **error** (string) - The standard error of the executed command, if any. - **return_code** (integer) - The exit code of the executed command. #### Response Example ```json { "output": "your-hostname\n", "error": "", "return_code": 0 } ``` ### Deployment Scenarios | Deployment | use_server_proxy | |--------------------------------------|------------------| | Server native on host, client on host| False (default) | | Server in Docker, client on host | True | | Server in Docker, client in same net | False | | Kubernetes with proper networking | False | ``` -------------------------------- ### Configure OpensandboxProvider using Environment Variables Source: https://context7.com/shkarupa-alex/deepagents-opensandbox/llms.txt This code example illustrates how to configure the OpensandboxProvider by setting environment variables for API key and server domain. The provider automatically reads these variables, simplifying configuration for different deployment environments. It includes creating a sandbox, executing a command, and deleting the sandbox. ```python import os from deepagents_opensandbox import OpensandboxProvider # Set environment variables os.environ["OPEN_SANDBOX_API_KEY"] = "your-secret-api-key" os.environ["OPEN_SANDBOX_DOMAIN"] = "sandbox.example.com:8080" # Provider reads from environment automatically provider = OpensandboxProvider() sandbox = provider.get_or_create(image="ubuntu:22.04") result = sandbox.execute("uname -a") print(result.output) provider.delete(sandbox_id=sandbox.id) ``` -------------------------------- ### Install deepagents-opensandbox Source: https://github.com/shkarupa-alex/deepagents-opensandbox/blob/master/README.md Installs the deepagents-opensandbox package using pip. This is the primary method for adding the package to your Python environment. ```bash pip install deepagents-opensandbox ``` -------------------------------- ### Upload Files to OpenSandbox Source: https://context7.com/shkarupa-alex/deepagents-opensandbox/llms.txt Shows how to upload single and multiple files to a sandbox container using the `OpensandboxBackend.upload_files` method. It includes examples of verifying the upload and executing uploaded scripts. ```python from opensandbox.sync.sandbox import SandboxSync from deepagents_opensandbox import OpensandboxBackend sandbox = SandboxSync.create("python:3.11") backend = OpensandboxBackend(sandbox=sandbox) responses = backend.upload_files([ ("/tmp/hello.txt", b"Hello, World!") ]) print(f"Path: {responses[0].path}") # /tmp/hello.txt print(f"Error: {responses[0].error}") # None responses = backend.upload_files([ ("/workspace/script.py", b"print('Hello from Python!')"), ("/workspace/data.json", b'{"key": "value"}'), ("/workspace/config.yaml", b"setting: true") ]) for resp in responses: if resp.error is None: print(f"Uploaded: {resp.path}") else: print(f"Failed: {resp.path} - {resp.error}") result = backend.execute("cat /workspace/script.py") print(result.output) # print('Hello from Python!') result = backend.execute("python /workspace/script.py") print(result.output) # Hello from Python! sandbox.kill() sandbox.close() ``` -------------------------------- ### Initialize and Use OpensandboxProvider Source: https://github.com/shkarupa-alex/deepagents-opensandbox/blob/master/README.md Demonstrates initializing the OpensandboxProvider, creating or retrieving a sandbox environment, executing a command within it, and cleaning up the sandbox. It relies on environment variables OPEN_SANDBOX_API_KEY and OPEN_SANDBOX_DOMAIN for configuration. ```python from deepagents_opensandbox import OpensandboxProvider # Initialize the provider (uses OPEN_SANDBOX_API_KEY and OPEN_SANDBOX_DOMAIN env vars) provider = OpensandboxProvider() # Create a new sandbox sandbox = provider.get_or_create(image="python:3.11") # Execute a command result = sandbox.execute("echo 'Hello World'") print(result.output) # Clean up provider.delete(sandbox_id=sandbox.id) ``` -------------------------------- ### Initialize and Manage Sandbox Lifecycle with OpensandboxProvider (Python) Source: https://context7.com/shkarupa-alex/deepagents-opensandbox/llms.txt Demonstrates how to initialize OpensandboxProvider, configure it via environment variables or constructor, create or retrieve a sandbox instance with custom settings (image, timeouts, resources), execute commands, and clean up the sandbox. Caching of sandbox instances is also shown. ```python import os from deepagents_opensandbox import OpensandboxProvider # Configure via environment variables or constructor os.environ["OPEN_SANDBOX_API_KEY"] = "your-api-key" os.environ["OPEN_SANDBOX_DOMAIN"] = "localhost:8080" # Initialize provider with default settings provider = OpensandboxProvider() # Or with explicit configuration provider = OpensandboxProvider( api_key="your-api-key", domain="localhost:8080", protocol="http", use_server_proxy=False # Set True when server runs in Docker, client on host ) # Create a new sandbox with custom settings sandbox = provider.get_or_create( image="python:3.11", timeout=600, # Sandbox lifetime in seconds ready_timeout=120, # Max wait time for sandbox ready resource={"cpu": "1", "memory": "2Gi"} # Resource limits ) # Execute commands result = sandbox.execute("python --version") print(f"Exit code: {result.exit_code}") print(f"Output: {result.output}") # Output: Python 3.11.x # Provider caches sandboxes - subsequent calls return same instance sandbox2 = provider.get_or_create(sandbox_id=sandbox.id) assert sandbox is sandbox2 # Same cached instance # Clean up when done provider.delete(sandbox_id=sandbox.id) # Delete is idempotent - safe to call multiple times provider.delete(sandbox_id=sandbox.id) # No error ``` -------------------------------- ### Directly Use OpensandboxBackend with SandboxSync Source: https://github.com/shkarupa-alex/deepagents-opensandbox/blob/master/README.md Shows how to use the OpensandboxBackend directly by first creating a sandbox instance using SandboxSync, then initializing the backend with this sandbox. It executes a command and then properly terminates the sandbox. ```python from opensandbox.sync.sandbox import SandboxSync from deepagents_opensandbox import OpensandboxBackend sandbox = SandboxSync.create("python:3.11") backend = OpensandboxBackend(sandbox=sandbox) result = backend.execute("python --version") print(result.output) sandbox.kill() sandbox.close() ``` -------------------------------- ### Create and Execute Commands in OpenSandbox Source: https://context7.com/shkarupa-alex/deepagents-opensandbox/llms.txt Demonstrates creating a sandbox directly using OpenSandbox SDK, wrapping it with DeepAgents backend, accessing the sandbox ID, and executing shell commands with and without timeouts. It also shows how to handle command failures and capture stderr. ```python from opensandbox.sync.sandbox import SandboxSync from opensandbox.sync.connection_config import ConnectionConfigSync from datetime import timedelta from deepagents_opensandbox import OpensandboxBackend config = ConnectionConfigSync(use_server_proxy=True) sandbox = SandboxSync.create( "python:3.11", timeout=timedelta(seconds=600), ready_timeout=timedelta(seconds=120), connection_config=config ) backend = OpensandboxBackend(sandbox=sandbox) print(f"Sandbox ID: {backend.id}") result = backend.execute("echo 'Hello, World!'") print(f"Exit code: {result.exit_code}") # 0 print(f"Output: {result.output}") # Hello, World! result = backend.execute("sleep 5 && echo done", timeout=10) print(result.output) # done result = backend.execute("exit 42") print(f"Exit code: {result.exit_code}") # 42 result = backend.execute("echo 'error message' >&2") print(result.output) # error message sandbox.kill() sandbox.close() ``` -------------------------------- ### Async Sandbox Management with OpensandboxProvider (Python) Source: https://context7.com/shkarupa-alex/deepagents-opensandbox/llms.txt Shows how to use the asynchronous interface of OpensandboxProvider for non-blocking sandbox creation and deletion. This is suitable for async applications and concurrent sandbox management. It demonstrates async creation, synchronous command execution within the async sandbox, and async deletion. ```python import asyncio from deepagents_opensandbox import OpensandboxProvider async def run_async_sandbox(): provider = OpensandboxProvider(use_server_proxy=True) # Async sandbox creation - non-blocking sandbox = await provider.aget_or_create( image="python:3.11", timeout=300, ready_timeout=120 ) try: # Execute commands (sync execution on async-created sandbox) result = sandbox.execute("echo 'Hello from async sandbox!'") print(f"Output: {result.output}") # Output: Hello from async sandbox! # Run Python code result = sandbox.execute("python -c \"print(2 + 2)\"" ) # Escaped quotes for inner python command print(f"Result: {result.output.strip()}") # Result: 4 finally: # Async delete - uses native async kill/close await provider.adelete(sandbox_id=sandbox.id) asyncio.run(run_async_sandbox()) ``` -------------------------------- ### Run Integration Tests with pytest Source: https://github.com/shkarupa-alex/deepagents-opensandbox/blob/master/README.md Runs integration tests against a real OpenSandbox server. This command requires setting the OPEN_SANDBOX_DOMAIN environment variable and uses `use_server_proxy=True` for host-to-Docker communication. The `-k integration` flag filters for integration tests. ```bash OPEN_SANDBOX_DOMAIN=localhost:8090 uv run python -m pytest deepagents_opensandbox/ -v -k integration ``` -------------------------------- ### Download Files from OpenSandbox Source: https://context7.com/shkarupa-alex/deepagents-opensandbox/llms.txt Illustrates how to download single and multiple files from a sandbox container using `OpensandboxBackend.download_files`. It covers handling various error conditions such as file not found, attempting to download directories, and permission denied. ```python from opensandbox.sync.sandbox import SandboxSync from deepagents_opensandbox import OpensandboxBackend sandbox = SandboxSync.create("python:3.11") backend = OpensandboxBackend(sandbox=sandbox) backend.execute("echo 'Hello from sandbox!' > /tmp/output.txt") responses = backend.download_files(["/tmp/output.txt"]) print(f"Path: {responses[0].path}") # /tmp/output.txt print(f"Content: {responses[0].content}") # b'Hello from sandbox!\n' print(f"Error: {responses[0].error}") # None backend.execute("echo 'file1' > /tmp/a.txt && echo 'file2' > /tmp/b.txt") responses = backend.download_files(["/tmp/a.txt", "/tmp/b.txt"]) for resp in responses: if resp.error is None: print(f"{resp.path}: {resp.content.decode()}") else: print(f"{resp.path}: Error - {resp.error}") responses = backend.download_files(["/nonexistent/file.txt"]) print(f"Error: {responses[0].error}") # file_not_found responses = backend.download_files(["/tmp"]) print(f"Error: {responses[0].error}") # is_directory responses = backend.download_files(["/root/secret.txt"]) print(f"Error: {responses[0].error}") # permission_denied sandbox.kill() sandbox.close() ``` -------------------------------- ### Connect to Existing Sandbox with OpensandboxProvider (Python) Source: https://context7.com/shkarupa-alex/deepagents-opensandbox/llms.txt Illustrates how to connect to a pre-existing sandbox using its ID with the OpensandboxProvider. This allows for resuming work or sharing sandboxes across different processes. Both synchronous and asynchronous connection methods are shown. ```python from deepagents_opensandbox import OpensandboxProvider provider = OpensandboxProvider() # Connect to existing sandbox by ID sandbox = provider.get_or_create(sandbox_id="existing-sandbox-id") # Continue working with the sandbox result = sandbox.execute("ls -la /workspace") print(result.output) # Async connection async def connect_async(): sandbox = await provider.aget_or_create(sandbox_id="existing-sandbox-id") result = sandbox.execute("pwd") print(result.output) ``` -------------------------------- ### Configure Server Proxy Mode with OpensandboxProvider Source: https://context7.com/shkarupa-alex/deepagents-opensandbox/llms.txt This snippet demonstrates how to initialize the OpensandboxProvider in server proxy mode. This mode is essential when the OpenSandbox server is running in a Docker container and the client is on the host machine, ensuring all requests are routed through the server. It shows the creation of a sandbox, execution of a command, and subsequent deletion of the sandbox. ```python from deepagents_opensandbox import OpensandboxProvider provider_proxy = OpensandboxProvider( domain="localhost:8090", use_server_proxy=True ) sandbox = provider_proxy.get_or_create(image="python:3.11") result = sandbox.execute("hostname") print(result.output) provider_proxy.delete(sandbox_id=sandbox.id) ``` -------------------------------- ### Inherited BaseSandbox Methods in OpenSandbox Source: https://context7.com/shkarupa-alex/deepagents-opensandbox/llms.txt Demonstrates the use of inherited shell-based file operations from `BaseSandbox`, including `write`, `read`, `edit`, `grep_raw`, and `glob_info`, through the `OpensandboxBackend`. These methods allow for file manipulation and searching within the sandbox. ```python from opensandbox.sync.sandbox import SandboxSync from deepagents_opensandbox import OpensandboxBackend sandbox = SandboxSync.create("python:3.11") backend = OpensandboxBackend(sandbox=sandbox) backend.write("/workspace/example.py", "def hello():\n return 'Hello!'\n") content = backend.read("/workspace/example.py") print(content) backend.edit("/workspace/example.py", "Hello!", "World!") matches = backend.grep_raw("def", "/workspace") print(matches) files = backend.glob_info("/workspace/*.py") for f in files: print(f) sandbox.kill() sandbox.close() ``` -------------------------------- ### Format Code with Ruff Source: https://github.com/shkarupa-alex/deepagents-opensandbox/blob/master/README.md Formats the code using Ruff to ensure a consistent style across the project. This command automatically adjusts code to comply with formatting standards. ```bash uv run ruff format --check deepagents_opensandbox/ ``` -------------------------------- ### Lint Code with Ruff Source: https://github.com/shkarupa-alex/deepagents-opensandbox/blob/master/README.md Performs code linting using Ruff to check for style and potential errors. This command helps maintain code quality and consistency. ```bash uv run ruff check deepagents_opensandbox/ ``` -------------------------------- ### Configure OpensandboxProvider for Server Proxy Mode Source: https://github.com/shkarupa-alex/deepagents-opensandbox/blob/master/README.md Illustrates how to enable server proxy mode in OpensandboxProvider by setting `use_server_proxy=True`. This is necessary when the OpenSandbox server runs inside Docker and the client is on the host machine, as container IPs may not be directly reachable. ```python provider = OpensandboxProvider(use_server_proxy=True) ``` -------------------------------- ### Configure Server Proxy Mode in OpenSandbox Source: https://context7.com/shkarupa-alex/deepagents-opensandbox/llms.txt Explains how to configure the `OpensandboxProvider` for server proxy mode, which is useful in deployment scenarios where direct container access is not feasible. It contrasts this with the default direct mode. ```python from deepagents_opensandbox import OpensandboxProvider # Direct mode (default) - SDK connects to container IPs directly # Use when: client and containers on same network provider_direct = OpensandboxProvider( domain="localhost:8080", use_server_proxy=False # Default ) # Server proxy mode - SDK connects to the proxy server, which then connects to containers # Use when: client cannot reach container IPs directly (e.g., different networks, firewalls) provider_proxy = OpensandboxProvider( domain="proxy.example.com:8080", use_server_proxy=True ) ``` -------------------------------- ### Run Unit Tests with pytest Source: https://github.com/shkarupa-alex/deepagents-opensandbox/blob/master/README.md Executes unit tests for the deepagents-opensandbox package using pytest. These tests are mocked and do not require a running OpenSandbox server. ```bash uv run python -m pytest deepagents_opensandbox/ -v ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.