> ## Documentation Index
> Fetch the complete documentation index at: https://docs.leeroo.com/llms.txt
> Use this file to discover all available pages before exploring further.

# API Reference

> Complete API documentation for the deployment module

## Module Exports

```python theme={null}
from kapso.deployment import (
    # Main factory
    DeploymentFactory,
    
    # Enums and configs
    DeployStrategy,
    DeployConfig,
    
    # Data classes
    DeploymentSetting,
    AdaptationResult,
    DeploymentInfo,
    
    # Base classes
    Software,
)
```

***

## DeploymentFactory

Factory for creating deployed Software instances.

### Methods

#### create()

Create a deployed Software instance.

```python theme={null}
@classmethod
def create(
    cls,
    strategy: DeployStrategy,
    config: DeployConfig,
    strategies: Optional[List[str]] = None,
) -> Software
```

**Parameters:**

| Parameter    | Type             | Description                                    |
| ------------ | ---------------- | ---------------------------------------------- |
| `strategy`   | `DeployStrategy` | Deployment target (AUTO, LOCAL, DOCKER, etc.)  |
| `config`     | `DeployConfig`   | Deployment configuration                       |
| `strategies` | `List[str]`      | Optional list of allowed strategies (for AUTO) |

**Returns:** `Software` instance with unified interface

**Raises:**

* `ValueError` if strategy not in allowed list
* `RuntimeError` if adaptation fails

**Example:**

```python theme={null}
from kapso.deployment import DeploymentFactory, DeployStrategy, DeployConfig

config = DeployConfig(
    solution=my_solution,
    env_vars={"API_KEY": "xxx"},
    timeout=300,
)

# Auto-select best strategy
deployed_program = DeploymentFactory.create(DeployStrategy.AUTO, config)

# Force specific strategy
deployed_program = DeploymentFactory.create(DeployStrategy.MODAL, config)

# Restrict to certain strategies
deployed_program = DeploymentFactory.create(
    DeployStrategy.AUTO, 
    config,
    strategies=["local", "docker"]
)
```

***

#### list\_strategies()

List all available deployment strategies.

```python theme={null}
@classmethod
def list_strategies(cls) -> List[str]
```

**Returns:** List of strategy names

**Example:**

```python theme={null}
strategies = DeploymentFactory.list_strategies()
print(strategies)
# ['bentoml', 'docker', 'langgraph', 'local', 'modal']
```

***

#### explain\_strategy()

Get explanation of a deployment strategy.

```python theme={null}
@classmethod
def explain_strategy(cls, strategy: str) -> str
```

**Parameters:**

| Parameter  | Type  | Description   |
| ---------- | ----- | ------------- |
| `strategy` | `str` | Strategy name |

**Returns:** One-line description from selector instruction

**Example:**

```python theme={null}
desc = DeploymentFactory.explain_strategy("modal")
print(desc)
# "Serverless GPU deployment on Modal.com with auto-scaling."
```

***

#### print\_strategies\_info()

Print information about all deployment strategies.

```python theme={null}
@classmethod
def print_strategies_info(cls) -> None
```

**Example:**

```python theme={null}
DeploymentFactory.print_strategies_info()
# Available Deployment Strategies:
# ==================================================
#   bentoml: Production ML service deployment...
#   docker: Run in an isolated Docker container...
#   ...
```

***

## DeployStrategy

Enum of available deployment strategies. **Auto-generated** from `strategies/` directory.

```python theme={null}
from kapso.deployment import DeployStrategy

# Always available
DeployStrategy.AUTO      # Let system choose

# Discovered from strategies/
DeployStrategy.LOCAL     # Local Python process
DeployStrategy.DOCKER    # Docker container
DeployStrategy.MODAL     # Modal.com serverless
DeployStrategy.BENTOML   # BentoML/BentoCloud
DeployStrategy.LANGGRAPH # LangGraph Platform
```

**Usage:**

```python theme={null}
# Use enum value
strategy = DeployStrategy.MODAL

# Get string value
print(strategy.value)  # "modal"

# Compare
if strategy == DeployStrategy.AUTO:
    print("Auto-selecting...")
```

***

## DeployConfig

Configuration for deploying software.

```python theme={null}
@dataclass
class DeployConfig:
    solution: SolutionResult
    env_vars: Dict[str, str] = None
    timeout: int = 300
    coding_agent: str = "claude_code"
```

**Fields:**

| Field          | Type             | Default         | Description                              |
| -------------- | ---------------- | --------------- | ---------------------------------------- |
| `solution`     | `SolutionResult` | Required        | The built solution from `Kapso.evolve()` |
| `env_vars`     | `Dict[str, str]` | `{}`            | Environment variables                    |
| `timeout`      | `int`            | `300`           | Execution timeout in seconds             |
| `coding_agent` | `str`            | `"claude_code"` | Coding agent for adaptation              |

**Properties:**

| Property    | Type  | Description                 |
| ----------- | ----- | --------------------------- |
| `code_path` | `str` | Path to the generated code  |
| `goal`      | `str` | The original goal/objective |

**Example:**

```python theme={null}
from kapso.deployment import DeployConfig

config = DeployConfig(
    solution=solution,
    env_vars={
        "API_KEY": "xxx",
        "DEBUG": "true",
    },
    timeout=600,
    coding_agent="gemini",
)

print(config.code_path)  # "/path/to/solution"
print(config.goal)       # "Create a sentiment API"
```

***

## Software (Abstract Base Class)

Unified interface for deployed software. Users interact with this class.

### Methods

#### run()

Execute the software with given inputs.

```python theme={null}
@abstractmethod
def run(self, inputs: Union[Dict, str, bytes]) -> Dict[str, Any]
```

**Parameters:**

| Parameter | Type                      | Description |
| --------- | ------------------------- | ----------- |
| `inputs`  | `Dict`, `str`, or `bytes` | Input data  |

**Returns:** Normalized response dictionary

**Response Format:**

```python theme={null}
# Success
{
    "status": "success",
    "output": {...}  # Your result
}

# Error
{
    "status": "error",
    "error": "Error message"
}
```

**Example:**

```python theme={null}
result = deployed_program.run({"text": "hello"})

if result["status"] == "success":
    print(result["output"])
else:
    print(f"Error: {result['error']}")
```

***

#### stop()

Stop the software and cleanup resources.

```python theme={null}
@abstractmethod
def stop(self) -> None
```

**Behavior by Strategy:**

| Strategy      | What `stop()` Does                                      |
| ------------- | ------------------------------------------------------- |
| **LOCAL**     | Unloads Python module from `sys.modules`                |
| **DOCKER**    | Stops and removes the Docker container                  |
| **MODAL**     | Runs `modal app stop` to terminate the deployment       |
| **BENTOML**   | Runs `bentoml deployment terminate` to stop the service |
| **LANGGRAPH** | Deletes the conversation thread and disconnects         |

**Example:**

```python theme={null}
deployed_program.stop()
print(deployed_program.is_healthy())  # False
```

***

#### start()

Start or restart a stopped deployment.

```python theme={null}
@abstractmethod
def start(self) -> None
```

**Behavior by Strategy:**

| Strategy      | What `start()` Does                               |
| ------------- | ------------------------------------------------- |
| **LOCAL**     | Reloads the Python module                         |
| **DOCKER**    | Creates and starts a new container                |
| **MODAL**     | Re-lookups the Modal function                     |
| **BENTOML**   | Re-deploys by running `deploy.py` from code\_path |
| **LANGGRAPH** | Reconnects to LangGraph Platform                  |

**Example:**

```python theme={null}
# After stop()
deployed_program.stop()
print(deployed_program.is_healthy())  # False

# Restart
deployed_program.start()
print(deployed_program.is_healthy())  # True

# Can run again
result = deployed_program.run({"text": "hello again"})
```

***

#### logs()

Get execution logs.

```python theme={null}
@abstractmethod
def logs(self) -> str
```

**Returns:** Log content as string

**Example:**

```python theme={null}
print(deployed_program.logs())
# Initialized local deployment
# run() called with: {"text": "hello"}
# run() completed: status=success
```

***

#### is\_healthy()

Check if software is running and healthy.

```python theme={null}
@abstractmethod
def is_healthy(self) -> bool
```

**Returns:** `True` if healthy, `False` otherwise

**Example:**

```python theme={null}
if deployed_program.is_healthy():
    result = deployed_program.run(inputs)
else:
    print("Software not healthy!")
```

***

#### name (property)

Return the deployment strategy name.

```python theme={null}
@property
@abstractmethod
def name(self) -> str
```

**Example:**

```python theme={null}
print(deployed_program.name)  # "modal"
```

***

### Convenience Methods

#### **call**()

Shorthand for `run()`.

```python theme={null}
# These are equivalent
result = deployed_program.run(inputs)
result = deployed_program(inputs)
```

***

#### run\_batch()

Run multiple inputs in sequence.

```python theme={null}
def run_batch(self, inputs_list: List[Any]) -> List[Dict[str, Any]]
```

**Example:**

```python theme={null}
results = deployed_program.run_batch([
    {"text": "hello"},
    {"text": "world"},
    {"text": "test"},
])

for result in results:
    print(result["output"])
```

***

#### Context Manager Support

```python theme={null}
with DeploymentFactory.create(strategy, config) as deployed_program:
    result = deployed_program.run(inputs)
# deployed_program.stop() called automatically
```

***

## DeployedSoftware

Concrete implementation of `Software`. Wraps any runner with unified interface.

### Additional Methods

#### get\_adapted\_path()

Get path to the adapted code.

```python theme={null}
def get_adapted_path(self) -> str
```

**Example:**

```python theme={null}
path = deployed_program.get_adapted_path()
print(path)  # "/path/to/solution_adapted_modal"
```

***

#### get\_endpoint()

Get HTTP endpoint if applicable.

```python theme={null}
def get_endpoint(self) -> Optional[str]
```

**Returns:** Endpoint URL or `None`

**Example:**

```python theme={null}
endpoint = deployed_program.get_endpoint()
if endpoint:
    print(f"API available at: {endpoint}")
```

***

#### get\_deployment\_info()

Get full deployment metadata.

```python theme={null}
def get_deployment_info(self) -> Dict[str, Any]
```

**Returns:**

```python theme={null}
{
    "strategy": "modal",
    "provider": "modal",
    "endpoint": "https://...",
    "adapted_path": "/path/to/...",
    "adapted_files": ["modal_app.py", "main.py"],
    "resources": {"gpu": "T4", "memory": "16Gi"},
}
```

***

#### get\_strategy()

Get the deployment strategy name.

```python theme={null}
def get_strategy(self) -> str
```

***

#### get\_provider()

Get the cloud provider name.

```python theme={null}
def get_provider(self) -> Optional[str]
```

***

## Data Classes

### DeploymentSetting

Result of strategy selection.

```python theme={null}
@dataclass
class DeploymentSetting:
    strategy: str              # "local", "docker", "modal", etc.
    provider: Optional[str]    # Cloud provider name
    resources: Dict[str, Any]  # Resource requirements
    interface: str             # "function", "http", etc.
    reasoning: str             # Why this was selected
```

***

### AdaptationResult

Result of code adaptation.

```python theme={null}
@dataclass
class AdaptationResult:
    success: bool
    adapted_path: str           # Path to adapted repo
    run_interface: Dict[str, Any]
    files_changed: List[str] = field(default_factory=list)
    error: Optional[str] = None
```

***

### DeploymentInfo

Metadata about the deployment.

```python theme={null}
@dataclass
class DeploymentInfo:
    strategy: str
    provider: Optional[str] = None
    endpoint: Optional[str] = None
    adapted_path: str = ""
    adapted_files: List[str] = field(default_factory=list)
    resources: Dict[str, Any] = field(default_factory=dict)
```

***

## SelectorAgent

LLM-based strategy selection agent.

```python theme={null}
from kapso.deployment.selector.agent import SelectorAgent
```

### Methods

#### select()

Select deployment configuration for a solution.

```python theme={null}
def select(
    self,
    solution: SolutionResult,
    allowed_strategies: Optional[List[str]] = None,
    resources: Optional[Dict[str, Any]] = None,
) -> DeploymentSetting
```

***

#### explain()

Get human-readable explanation of selection.

```python theme={null}
def explain(self, solution: SolutionResult) -> str
```

**Example:**

```python theme={null}
selector = SelectorAgent()
explanation = selector.explain(solution)
print(explanation)
# Deployment Selection Analysis
# ========================================
# 
# Strategy:  modal
# Interface: function
# Provider:  modal
# Resources: {'gpu': 'T4', 'memory': '16Gi'}
# 
# Reasoning: GPU workload detected (torch dependency)
```

***

## AdapterAgent

Code transformation and deployment agent.

```python theme={null}
from kapso.deployment.adapter.agent import AdapterAgent
```

### Methods

#### adapt()

Adapt a solution for deployment.

```python theme={null}
def adapt(
    self,
    solution: SolutionResult,
    setting: DeploymentSetting,
    allowed_strategies: Optional[List[str]] = None,
) -> AdaptationResult
```

**Note:** Creates a copy of the solution at `{code_path}_adapted_{strategy}`. Original is never modified.

***

## StrategyRegistry

Auto-discovery system for deployment strategies.

```python theme={null}
from kapso.deployment.strategies import StrategyRegistry
```

### Methods

#### get()

Get singleton registry instance.

```python theme={null}
@classmethod
def get(cls) -> StrategyRegistry
```

***

#### list\_strategies()

List available strategy names.

```python theme={null}
def list_strategies(self, allowed: Optional[List[str]] = None) -> List[str]
```

***

#### get\_strategy()

Get strategy config by name.

```python theme={null}
def get_strategy(self, name: str) -> DeployStrategyConfig
```

***

#### get\_selector\_instruction()

Get selector instruction content.

```python theme={null}
def get_selector_instruction(self, name: str) -> str
```

***

#### get\_adapter\_instruction()

Get adapter instruction content.

```python theme={null}
def get_adapter_instruction(self, name: str) -> str
```

***

#### get\_runner\_class()

Get the runner class for a strategy.

```python theme={null}
def get_runner_class(self, name: str) -> type
```

***

#### get\_default\_run\_interface()

Get default run interface from config.yaml.

```python theme={null}
def get_default_run_interface(self, name: str) -> Dict[str, Any]
```

***

## Runner (Abstract Base Class)

Base class for strategy-specific runners.

```python theme={null}
from kapso.deployment.strategies.base import Runner
```

### Lifecycle

Runners follow this lifecycle:

1. `__init__()` → Ready state
2. `run()` → Execute (can be called multiple times)
3. `stop()` → Stopped state (resources cleaned up)
4. `start()` → Ready state (can run again)

```
┌─────────────┐    stop()    ┌─────────────┐
│   READY     │ ──────────>  │   STOPPED   │
│ is_healthy  │              │ !is_healthy │
│   = True    │  <──────────  │   = False   │
└─────────────┘    start()   └─────────────┘
```

### Abstract Methods

```python theme={null}
class Runner(ABC):
    @abstractmethod
    def run(self, inputs: Union[Dict, str, bytes]) -> Any:
        """Execute with inputs and return result."""
        pass
    
    @abstractmethod
    def start(self) -> None:
        """Start or restart the runner."""
        pass
    
    @abstractmethod
    def stop(self) -> None:
        """Stop and cleanup resources."""
        pass
    
    @abstractmethod
    def is_healthy(self) -> bool:
        """Check if runner is healthy."""
        pass
    
    def get_logs(self) -> str:
        """Get runner logs (default: empty)."""
        return ""
```

***

## Complete Usage Example

```python theme={null}
from kapso.kapso import Kapso
from kapso.deployment import DeploymentFactory, DeployStrategy, DeployConfig

# 1. Build a solution
kapso = Kapso()
solution = kapso.evolve("Create a text embedding API using sentence-transformers")

# 2. Deploy with auto-selection
deployed_program = kapso.deploy(solution)
print(f"Deployed using: {deployed_program.name}")
print(f"Endpoint: {deployed_program.get_endpoint()}")

# 3. Use the deployed_program
result = deployed_program.run({"text": "Hello world"})
if result["status"] == "success":
    embeddings = result["output"]["embeddings"]
    print(f"Got {len(embeddings)} dimensional embeddings")

# 4. Batch processing
texts = ["text 1", "text 2", "text 3"]
results = deployed_program.run_batch([{"text": t} for t in texts])

# 5. Check health
if deployed_program.is_healthy():
    print("Service is healthy")

# 6. Get logs for debugging
print(deployed_program.logs())

# 7. Get deployment details
info = deployed_program.get_deployment_info()
print(f"Strategy: {info['strategy']}")
print(f"Adapted path: {info['adapted_path']}")

# 8. Stop and restart (full lifecycle)
deployed_program.stop()
print(f"Is healthy after stop: {deployed_program.is_healthy()}")  # False

deployed_program.start()
print(f"Is healthy after start: {deployed_program.is_healthy()}")  # True

# 9. Run again after restart
result = deployed_program.run({"text": "Working again!"})

# 10. Final cleanup
deployed_program.stop()
```

***

## Error Handling

```python theme={null}
try:
    deployed_program = DeploymentFactory.create(DeployStrategy.MODAL, config)
    result = deployed_program.run(inputs)
    
    if result["status"] == "error":
        print(f"Execution error: {result['error']}")
        
except ValueError as e:
    print(f"Invalid configuration: {e}")
    
except RuntimeError as e:
    print(f"Deployment failed: {e}")
    
finally:
    if 'deployed_program' in locals():
        deployed_program.stop()
```

***

## Environment Variables

| Variable             | Strategy  | Description               |
| -------------------- | --------- | ------------------------- |
| `MODAL_TOKEN_ID`     | Modal     | Modal authentication      |
| `MODAL_TOKEN_SECRET` | Modal     | Modal authentication      |
| `LANGSMITH_API_KEY`  | LangGraph | LangSmith API key         |
| `BENTOML_API_TOKEN`  | BentoML   | BentoCloud authentication |
