Skip to main content
The Runtimes Service gives you programmatic control over the environments in which your agents operate on the Kubiya platform. It acts as the main interface for discovering, configuring, and validating agent runtimes, whether you are using built-in types like agno and claude_code, or custom runtimes tailored to your needs. With this service, you can:
  • List and filter available runtimes to see what execution environments are available for your agents, including their features and status.
  • Retrieve detailed runtime requirements to understand what dependencies, features, or models are needed for each runtime type.
  • Validate runtime configurations before deploying agents, ensuring your setup meets all requirements and will work as expected.
This service is especially valuable for platform administrators and advanced users who want to ensure agents are deployed in the right environment, with all necessary features and compliance. By using the Runtimes Service, you can confidently manage agent execution, avoid misconfigurations, and streamline the deployment process.
For conceptual information about runtimes and how they’re used in agents, see Runtimes Core Concepts.

Overview

The Runtimes Service provides a set of high-level methods designed to be intuitive and flexible, supporting a wide range of operational and administrative tasks:
  • list(): Retrieve all available runtimes, with details about their type, features, and status. This is the primary entry point for discovering which execution environments are available in your workspace.
  • get_requirements(runtime_id): Fetch detailed requirements for a specific runtime, including required features, model compatibility, and environment settings. Use this to ensure your agent configuration matches the runtime’s needs.
  • validate(runtime_config): Validate a runtime configuration before deploying an agent. This helps catch errors early and ensures your deployment will succeed without unexpected issues.
By using these methods, you can build robust, dynamic workflows that adapt to changes in runtime availability, enforce organizational policies, and provide a seamless experience for both developers and end-users. The following sections provide practical guidance, detailed examples, and best practices for leveraging the Runtimes Service effectively in your own projects.

Quick Start

from kubiya import ControlPlaneClient

# Initialize client
client = ControlPlaneClient(api_key="your-api-key")

# List all available runtimes
runtimes = client.runtimes.list()
for runtime in runtimes:
    print(f"Runtime: {runtime['name']} - Type: {runtime['type']}")

# Get requirements for a specific runtime
requirements = client.runtimes.get_requirements("claude_code")
print(f"Required features: {requirements}")

List Runtimes

List all available agent runtime types.

Basic Listing

# List all runtimes
runtimes = client.runtimes.list()

for runtime in runtimes:
    print(f"""
    Name: {runtime['name']}
    Type: {runtime['type']}
    Description: {runtime.get('description', 'N/A')}
    Status: {runtime.get('status', 'active')}
    """)

Extract Runtime Information

def get_runtime_by_name(name: str):
    """Find a runtime by name"""
    runtimes = client.runtimes.list()

    for runtime in runtimes:
        if runtime['name'] == name:
            return runtime

    return None

# Usage
agno_runtime = get_runtime_by_name("agno")
if agno_runtime:
    print(f"Runtime: {agno_runtime['name']}")
    print(f"Description: {agno_runtime.get('description')}")

claude_code_runtime = get_runtime_by_name("claude_code")
if claude_code_runtime:
    print(f"Runtime: {claude_code_runtime['name']}")
    print(f"Features: {claude_code_runtime.get('features', [])}")

Filter Runtimes by Type

def filter_runtimes_by_type(runtime_type: str):
    """Filter runtimes by type"""
    runtimes = client.runtimes.list()

    return [r for r in runtimes if r.get('type') == runtime_type]

# Usage
builtin_runtimes = filter_runtimes_by_type("builtin")
print(f"Built-in runtimes: {len(builtin_runtimes)}")

custom_runtimes = filter_runtimes_by_type("custom")
print(f"Custom runtimes: {len(custom_runtimes)}")

Get Runtime Requirements

Get runtime-specific requirements for a runtime.

Basic Requirements Check

# Get requirements for claude_code runtime
requirements = client.runtimes.get_requirements("claude_code")

print(f"Runtime Requirements:")
print(f"  Model: {requirements.get('model_requirements', {})}")
print(f"  Features: {requirements.get('required_features', [])}")
print(f"  Environment: {requirements.get('environment', {})}")

Check Runtime Compatibility

def check_runtime_compatibility(runtime_id: str):
    """Check if a runtime has all required features"""
    try:
        requirements = client.runtimes.get_requirements(runtime_id)

        return {
            "runtime_id": runtime_id,
            "has_requirements": True,
            "required_features": requirements.get('required_features', []),
            "optional_features": requirements.get('optional_features', []),
            "model_requirements": requirements.get('model_requirements', {}),
        }
    except Exception as e:
        return {
            "runtime_id": runtime_id,
            "has_requirements": False,
            "error": str(e)
        }

# Usage
agno_compat = check_runtime_compatibility("agno")
print(f"Agno Runtime Compatibility: {agno_compat}")

claude_compat = check_runtime_compatibility("claude_code")
print(f"Claude Code Runtime Compatibility: {claude_compat}")

Compare Runtime Requirements

def compare_runtimes(runtime_ids: list):
    """Compare requirements across multiple runtimes"""
    comparison = {}

    for runtime_id in runtime_ids:
        try:
            requirements = client.runtimes.get_requirements(runtime_id)
            comparison[runtime_id] = {
                "required_features": requirements.get('required_features', []),
                "model_requirements": requirements.get('model_requirements', {}),
                "environment": requirements.get('environment', {})
            }
        except Exception as e:
            comparison[runtime_id] = {"error": str(e)}

    return comparison

# Usage
comparison = compare_runtimes(["agno", "claude_code", "standard"])

print("Runtime Comparison:")
for runtime_id, reqs in comparison.items():
    print(f"\n{runtime_id}:")
    if "error" in reqs:
        print(f"  Error: {reqs['error']}")
    else:
        print(f"  Features: {reqs.get('required_features', [])}")

Validate Runtime Configuration

Validate a runtime configuration before deployment.

Basic Validation

# Validate a runtime configuration
runtime_config = {
    "runtime_type": "agno",
    "model": "kubiya/claude-sonnet-4",
    "features": ["code_execution", "web_browsing"],
    "environment": {
        "timeout": 300,
        "max_retries": 3
    }
}

validation_result = client.runtimes.validate(runtime_config)

if validation_result.get('valid'):
    print("✅ Configuration is valid!")
else:
    print("❌ Configuration is invalid:")
    for error in validation_result.get('errors', []):
        print(f"  - {error}")

Validate with Error Handling

from kubiya.resources.exceptions import RuntimeError

def validate_runtime_config_safe(config: dict):
    """Validate runtime configuration with error handling"""
    try:
        result = client.runtimes.validate(config)

        if result.get('valid'):
            return {
                "success": True,
                "message": "Configuration is valid",
                "validated_config": result.get('validated_config', config)
            }
        else:
            return {
                "success": False,
                "message": "Configuration validation failed",
                "errors": result.get('errors', []),
                "warnings": result.get('warnings', [])
            }
    except RuntimeError as e:
        return {
            "success": False,
            "message": f"Validation error: {e}",
            "errors": [str(e)]
        }

# Usage
config = {
    "runtime_type": "claude_code",
    "model": "kubiya/claude-sonnet-4",
}

result = validate_runtime_config_safe(config)
print(f"Validation result: {result['message']}")
if not result['success']:
    print(f"Errors: {result['errors']}")

Pre-deployment Validation

def pre_deployment_check(agent_config: dict):
    """Comprehensive pre-deployment runtime validation"""
    runtime_type = agent_config.get('runtime_type')

    if not runtime_type:
        return {"valid": False, "error": "No runtime type specified"}

    # Get runtime requirements
    try:
        requirements = client.runtimes.get_requirements(runtime_type)
    except RuntimeError as e:
        return {"valid": False, "error": f"Invalid runtime: {e}"}

    # Validate configuration
    try:
        validation = client.runtimes.validate(agent_config)

        return {
            "valid": validation.get('valid', False),
            "runtime_type": runtime_type,
            "requirements_met": validation.get('requirements_met', False),
            "errors": validation.get('errors', []),
            "warnings": validation.get('warnings', [])
        }
    except RuntimeError as e:
        return {"valid": False, "error": str(e)}

# Usage
agent_config = {
    "runtime_type": "agno",
    "model": "kubiya/claude-sonnet-4",
    "skills": ["kubernetes", "terraform"],
    "environment": {"timeout": 600}
}

check_result = pre_deployment_check(agent_config)
if check_result['valid']:
    print("✅ Ready for deployment")
else:
    print(f"❌ Pre-deployment check failed: {check_result.get('error')}")
    print(f"Errors: {check_result.get('errors', [])}")

Practical Examples

1. Runtime Selection Helper

Use this helper when you want to automatically select the most suitable runtime for your agent based on required features or model provider. This is useful for dynamic agent deployment or when your requirements may change over time.
def select_best_runtime(requirements: dict):
    """Select the best runtime based on requirements"""
    runtimes = client.runtimes.list()

    required_features = requirements.get('features', [])
    model_preference = requirements.get('model_provider', '')

    suitable_runtimes = []

    for runtime in runtimes:
        runtime_id = runtime.get('name')

        try:
            runtime_reqs = client.runtimes.get_requirements(runtime_id)
            runtime_features = runtime_reqs.get('supported_features', [])

            # Check if runtime supports all required features
            if all(feature in runtime_features for feature in required_features):
                suitable_runtimes.append({
                    "runtime_id": runtime_id,
                    "runtime": runtime,
                    "requirements": runtime_reqs,
                    "match_score": len(set(required_features) & set(runtime_features))
                })
        except RuntimeError:
            continue

    # Sort by match score
    suitable_runtimes.sort(key=lambda x: x['match_score'], reverse=True)

    return suitable_runtimes[0] if suitable_runtimes else None

# Usage
requirements = {
    "features": ["code_execution", "file_system_access"],
    "model_provider": "Anthropic"
}

best_runtime = select_best_runtime(requirements)
if best_runtime:
    print(f"Recommended runtime: {best_runtime['runtime_id']}")
    print(f"Match score: {best_runtime['match_score']}")

2. Runtime Compatibility Matrix

This example helps you generate a matrix comparing all available runtimes, their features, and compatibility. It’s valuable for platform administrators or teams evaluating which runtimes best fit their needs.
def generate_compatibility_matrix():
    """Generate a compatibility matrix for all runtimes"""
    runtimes = client.runtimes.list()

    matrix = {}

    for runtime in runtimes:
        runtime_id = runtime.get('name')

        try:
            requirements = client.runtimes.get_requirements(runtime_id)

            matrix[runtime_id] = {
                "name": runtime.get('name'),
                "type": runtime.get('type'),
                "features": requirements.get('supported_features', []),
                "model_compatibility": requirements.get('model_requirements', {}),
                "status": runtime.get('status', 'active')
            }
        except RuntimeError:
            matrix[runtime_id] = {"error": "Failed to get requirements"}

    return matrix

# Usage
matrix = generate_compatibility_matrix()

print("Runtime Compatibility Matrix:")
print(f"{'Runtime':<20} {'Type':<15} {'Features':<30} {'Status':<10}")
print("-" * 75)

for runtime_id, info in matrix.items():
    if "error" in info:
        print(f"{runtime_id:<20} {'ERROR':<15} {info['error']:<30} {'N/A':<10}")
    else:
        features = ", ".join(info['features'][:2]) + "..." if len(info['features']) > 2 else ", ".join(info['features'])
        print(f"{info['name']:<20} {info['type']:<15} {features:<30} {info['status']:<10}")

3. Runtime Configuration Builder

Use this builder class to construct and validate runtime configurations step by step. This approach is helpful for complex deployments where you want to ensure all configuration details are correct before deploying an agent.
class RuntimeConfigBuilder:
    """Helper class to build validated runtime configurations"""

    def __init__(self, client):
        self.client = client
        self.config = {}

    def set_runtime(self, runtime_type: str):
        """Set the runtime type"""
        self.config['runtime_type'] = runtime_type
        return self

    def set_model(self, model: str):
        """Set the model"""
        self.config['model'] = model
        return self

    def add_features(self, features: list):
        """Add features to the configuration"""
        self.config['features'] = features
        return self

    def set_environment(self, env_config: dict):
        """Set environment configuration"""
        self.config['environment'] = env_config
        return self

    def validate(self):
        """Validate the configuration"""
        return self.client.runtimes.validate(self.config)

    def build(self):
        """Build and return the configuration"""
        # Validate before building
        validation = self.validate()

        if not validation.get('valid'):
            raise ValueError(f"Invalid configuration: {validation.get('errors')}")

        return self.config

# Usage
builder = RuntimeConfigBuilder(client)

try:
    config = (builder
              .set_runtime("agno")
              .set_model("kubiya/claude-sonnet-4")
              .add_features(["code_execution", "web_browsing"])
              .set_environment({"timeout": 300, "max_retries": 3})
              .build())

    print(f"✅ Built valid configuration: {config}")
except ValueError as e:
    print(f"❌ Configuration error: {e}")

4. Runtime Health Monitor

Monitor the health status of all runtimes in your environment. This is useful for ongoing operations and maintenance, allowing you to quickly identify and address issues with inactive or unhealthy runtimes.
def monitor_runtime_health():
    """Monitor health of all runtimes"""
    runtimes = client.runtimes.list()

    health_status = {
        "healthy": [],
        "unhealthy": [],
        "unknown": []
    }

    for runtime in runtimes:
        runtime_id = runtime.get('name')
        status = runtime.get('status', 'unknown')

        if status == 'active':
            health_status['healthy'].append(runtime_id)
        elif status == 'inactive' or status == 'error':
            health_status['unhealthy'].append(runtime_id)
        else:
            health_status['unknown'].append(runtime_id)

    return health_status

# Usage
health = monitor_runtime_health()
print(f"Runtime Health Status:")
print(f"  ✅ Healthy: {len(health['healthy'])} - {health['healthy']}")
print(f"  ❌ Unhealthy: {len(health['unhealthy'])} - {health['unhealthy']}")
print(f"  ⚠️  Unknown: {len(health['unknown'])} - {health['unknown']}")

Error Handling

When working with runtimes, you may encounter errors such as missing runtimes, invalid configurations, or unavailable features. These examples show how to handle such errors gracefully and provide fallback options to keep your workflows running smoothly.
from kubiya.resources.exceptions import RuntimeError

try:
    # Try to get runtime requirements
    requirements = client.runtimes.get_requirements("non-existent-runtime")
except RuntimeError as e:
    print(f"Runtime error: {e}")
    # Handle error - maybe fall back to default runtime
    print("Falling back to default runtime")
    runtimes = client.runtimes.list()
    default_runtime = runtimes[0] if runtimes else None
    if default_runtime:
        print(f"Using runtime: {default_runtime['name']}")

# Validate with error handling
try:
    config = {"runtime_type": "invalid"}
    validation = client.runtimes.validate(config)

    if not validation.get('valid'):
        print(f"Configuration invalid: {validation.get('errors')}")
except RuntimeError as e:
    print(f"Validation error: {e}")

Best Practices

Follow these best practices to make your use of the Runtimes Service more robust, efficient, and maintainable. These patterns help you avoid common pitfalls and ensure your code is resilient to changes in runtime availability or configuration.

1. Cache Runtime Information

To reduce API calls and improve performance, cache runtime and requirements information locally after the first retrieval. This is especially useful in applications that repeatedly access the same runtime details.
# Cache runtimes to reduce API calls
class RuntimeCache:
    def __init__(self, client):
        self.client = client
        self._runtimes_cache = None
        self._requirements_cache = {}

    def get_runtimes(self):
        """Get cached runtimes"""
        if self._runtimes_cache is None:
            self._runtimes_cache = self.client.runtimes.list()
        return self._runtimes_cache

    def get_requirements(self, runtime_id: str):
        """Get cached requirements for a runtime"""
        if runtime_id not in self._requirements_cache:
            self._requirements_cache[runtime_id] = self.client.runtimes.get_requirements(runtime_id)
        return self._requirements_cache[runtime_id]

    def invalidate_cache(self):
        """Clear the cache"""
        self._runtimes_cache = None
        self._requirements_cache = {}

# Usage
cache = RuntimeCache(client)
runtimes = cache.get_runtimes()  # API call
runtimes_again = cache.get_runtimes()  # From cache

2. Always Validate Before Deployment

Always validate your runtime configuration before deploying an agent. This helps catch errors early and ensures your deployment will succeed without unexpected issues.
# Always validate runtime configuration before using
def deploy_agent_safe(agent_config: dict):
    """Deploy agent with pre-validation"""
    # Validate runtime configuration first
    validation = client.runtimes.validate(agent_config)

    if not validation.get('valid'):
        raise ValueError(f"Invalid runtime configuration: {validation.get('errors')}")

    # Proceed with deployment
    # ... deployment logic ...

    return {"success": True, "config": agent_config}

# Usage
config = {
    "runtime_type": "agno",
    "model": "kubiya/claude-sonnet-4"
}

try:
    result = deploy_agent_safe(config)
    print(f"✅ Agent deployed successfully")
except ValueError as e:
    print(f"❌ Deployment failed: {e}")

3. Check Requirements Before Configuration

Before building a runtime configuration, check the requirements for the selected runtime. This ensures your configuration will meet all necessary criteria and reduces the risk of deployment failures.
def build_config_from_requirements(runtime_id: str):
    """Build configuration based on runtime requirements"""
    # Get requirements first
    requirements = client.runtimes.get_requirements(runtime_id)

    # Build config based on requirements
    config = {
        "runtime_type": runtime_id,
        "features": requirements.get('required_features', []),
        "environment": requirements.get('default_environment', {})
    }

    # Add model if specified in requirements
    if 'model_requirements' in requirements:
        model_reqs = requirements['model_requirements']
        if 'default_model' in model_reqs:
            config['model'] = model_reqs['default_model']

    return config

# Usage
config = build_config_from_requirements("agno")
print(f"Generated configuration: {config}")

4. Handle Runtime Unavailability

Always provide a fallback mechanism in case your preferred runtime is unavailable. This keeps your application resilient and ensures continuity of service even if a runtime is removed or temporarily inaccessible.
def get_runtime_with_fallback(preferred_runtime: str, fallback_runtime: str = "agno"):
    """Get runtime with automatic fallback"""
    try:
        # Try to get preferred runtime requirements
        requirements = client.runtimes.get_requirements(preferred_runtime)
        return {
            "runtime_id": preferred_runtime,
            "requirements": requirements,
            "is_fallback": False
        }
    except RuntimeError as e:
        print(f"Preferred runtime unavailable: {e}")
        print(f"Falling back to: {fallback_runtime}")

        try:
            requirements = client.runtimes.get_requirements(fallback_runtime)
            return {
                "runtime_id": fallback_runtime,
                "requirements": requirements,
                "is_fallback": True
            }
        except RuntimeError:
            raise ValueError("Both preferred and fallback runtimes unavailable")

# Usage
runtime = get_runtime_with_fallback("custom-runtime", "agno")
print(f"Using runtime: {runtime['runtime_id']}")
if runtime['is_fallback']:
    print("⚠️  Using fallback runtime")

API Reference

Methods

MethodDescriptionParameters
list()List all available runtimesNone
get_requirements(runtime_id)Get runtime-specific requirementsruntime_id: Runtime identifier (e.g., ‘claude_code’)
validate(runtime_config)Validate runtime configurationruntime_config: Dictionary with runtime configuration

Runtime Object Structure

{
    "name": "string",                # Runtime name (e.g., "agno", "claude_code")
    "type": "string",                # Runtime type (e.g., "builtin", "custom")
    "description": "string",         # Runtime description
    "status": "string",              # Runtime status (e.g., "active", "inactive")
    "features": ["string"],          # Supported features
    "created_at": "string",          # Creation timestamp
    "updated_at": "string"           # Last update timestamp
}

Requirements Object Structure

{
    "required_features": ["string"],        # Required features
    "optional_features": ["string"],        # Optional features
    "supported_features": ["string"],       # All supported features
    "model_requirements": {                 # Model requirements
        "default_model": "string",
        "supported_providers": ["string"]
    },
    "environment": {                        # Environment configuration
        "timeout": int,
        "max_retries": int
    },
    "default_environment": dict            # Default environment settings
}

Validation Result Object Structure

{
    "valid": bool,                    # Whether configuration is valid
    "errors": ["string"],             # List of validation errors
    "warnings": ["string"],           # List of validation warnings
    "requirements_met": bool,         # Whether all requirements are met
    "validated_config": dict          # Validated configuration
}

Next Steps