Skip to main content
The EnvironmentVariables resource provides methods for managing environment variables inside sandboxes at runtime.

Accessing Environment Variables Resource

from hopx_ai import Sandbox

sandbox = Sandbox.create(template="code-interpreter")
env = sandbox.env  # Lazy-loaded resource

Getting Environment Variables

get_all()

Get all environment variables.
env_vars = sandbox.env.get_all()
print(env_vars.get("PATH"))
print(env_vars.get("HOME"))
Method Signature:
def get_all(self, *, timeout: Optional[int] = None) -> Dict[str, str]
Returns: Dictionary of all environment variables Example:
# Get all environment variables
env = sandbox.env.get_all()

# Print all variables
for key, value in env.items():
    print(f"{key}={value}")

# Access specific variables
path = env.get("PATH", "")
home = env.get("HOME", "")

get()

Get a specific environment variable value.
api_key = sandbox.env.get("API_KEY")
db_url = sandbox.env.get("DATABASE_URL", "postgres://localhost/db")
Method Signature:
def get(self, key: str, default: Optional[str] = None) -> Optional[str]
Parameters:
  • key (str): Environment variable name
  • default (str, optional): Default value if variable doesn’t exist
Returns: Variable value or default Example:
# Get with default
api_key = sandbox.env.get("API_KEY", "default-key")

# Check if exists
if sandbox.env.get("DEBUG"):
    print("Debug mode enabled")

Setting Environment Variables

set()

Set a single environment variable (merges with existing).
sandbox.env.set("API_KEY", "sk-prod-xyz")
sandbox.env.set("NODE_ENV", "production")
Method Signature:
def set(
    self,
    key: str,
    value: str,
    *,
    timeout: Optional[int] = None
) -> Dict[str, str]
Parameters:
  • key (str): Environment variable name
  • value (str): Environment variable value
  • timeout (int, optional): Request timeout
Returns: Updated dictionary of all environment variables Example:
# Set individual variables
sandbox.env.set("API_KEY", "sk-test-123")
sandbox.env.set("DEBUG", "true")
sandbox.env.set("NODE_ENV", "production")

set_all()

Replace all environment variables (destructive - removes existing vars not in the provided object).
sandbox.env.set_all({
    "API_KEY": "sk-prod-xyz",
    "DATABASE_URL": "postgres://localhost/db",
    "NODE_ENV": "production"
})
Method Signature:
def set_all(
    self,
    env_vars: Dict[str, str],
    *,
    timeout: Optional[int] = None
) -> Dict[str, str]
Warning: This replaces ALL existing environment variables. Use update() if you want to merge instead. Example:
# Replace all environment variables
sandbox.env.set_all({
    "API_KEY": "sk-prod-xyz",
    "DATABASE_URL": "postgres://localhost/db",
    "NODE_ENV": "production"
})

# Note: PATH, HOME, and other system variables are now removed!

update()

Update specific environment variables (merge with existing).
sandbox.env.update({
    "NODE_ENV": "production",
    "DEBUG": "false"
})
Method Signature:
def update(
    self,
    env_vars: Dict[str, str],
    *,
    timeout: Optional[int] = None
) -> Dict[str, str]
Note: This merges with existing variables. Existing variables not specified are preserved. Example:
# Add/update specific variables
sandbox.env.update({
    "API_KEY": "sk-prod-xyz",
    "DEBUG": "true"
})

# Existing variables like PATH, HOME, etc. are preserved

Deleting Environment Variables

delete()

Delete an environment variable.
sandbox.env.delete("DEBUG")
sandbox.env.delete("TEMP_TOKEN")
Method Signature:
def delete(
    self,
    key: str,
    *,
    timeout: Optional[int] = None
) -> Dict[str, str]
Parameters:
  • key (str): Environment variable name to delete
  • timeout (int, optional): Request timeout
Returns: Updated dictionary of all environment variables Example:
# Delete specific variable
sandbox.env.delete("DEBUG")

# Delete temporary token
sandbox.env.delete("TEMP_API_KEY")

Environment Variable Priority

When executing code or commands, environment variables are applied in this order:
  1. Execution-specific env vars (from run_code() or commands.run() env parameter)
  2. Global sandbox env vars (from sandbox.env)
  3. Agent default env vars (system defaults)
Example:
# Set global variable
sandbox.env.set("API_KEY", "sk-global")

# Override for specific execution
result = sandbox.run_code(
    'import os; print(os.environ.get("API_KEY"))',
    env={"API_KEY": "sk-local"}  # This takes precedence
)
# Output: sk-local

Best Practices

1. Use update() Instead of set_all()

Preserve system variables:
# Good: Merge with existing
sandbox.env.update({
    "API_KEY": "sk-prod-xyz",
    "DEBUG": "true"
})

# Bad: Removes system variables
sandbox.env.set_all({
    "API_KEY": "sk-prod-xyz",
    "DEBUG": "true"
})

2. Set Variables at Sandbox Creation

Set environment variables when creating the sandbox:
sandbox = Sandbox.create(
    template="code-interpreter",
    env_vars={
        "API_KEY": "sk-prod-xyz",
        "NODE_ENV": "production"
    }
)

3. Use Environment Variables for Secrets

Never hardcode secrets in code:
# Good: Use environment variables
sandbox.env.set("API_KEY", "sk-secret-key")
result = sandbox.run_code('import os; key = os.environ.get("API_KEY")')

# Bad: Hardcode in code
result = sandbox.run_code('key = "sk-secret-key"')

4. Clean Up Temporary Variables

Delete temporary variables when done:
# Set temporary variable
sandbox.env.set("TEMP_TOKEN", "temp-value")

# Use it
result = sandbox.run_code('import os; token = os.environ.get("TEMP_TOKEN")')

# Clean up
sandbox.env.delete("TEMP_TOKEN")

Examples

Application Configuration

# Set application environment
sandbox.env.update({
    "NODE_ENV": "production",
    "DEBUG": "false",
    "LOG_LEVEL": "info",
    "API_URL": "https://api.example.com"
})

# Verify
env = sandbox.env.get_all()
print(f"Environment: {env.get('NODE_ENV')}")
print(f"Debug: {env.get('DEBUG')}")

Database Connection

# Set database credentials
sandbox.env.update({
    "DB_HOST": "localhost",
    "DB_PORT": "5432",
    "DB_NAME": "mydb",
    "DB_USER": "user",
    "DB_PASSWORD": "secret"
})

# Use in code
result = sandbox.run_code(
    '''
import os
db_url = f"postgres://{os.environ['DB_USER']}:{os.environ['DB_PASSWORD']}@{os.environ['DB_HOST']}:{os.environ['DB_PORT']}/{os.environ['DB_NAME']}"
print(db_url)
'''
)

Multi-Stage Configuration

# Initial setup
sandbox.env.set("STAGE", "development")
sandbox.env.set("DEBUG", "true")

# Run development code
result = sandbox.run_code('print("Development mode")')

# Switch to production
sandbox.env.set("STAGE", "production")
sandbox.env.set("DEBUG", "false")

# Run production code
result = sandbox.run_code('print("Production mode")')