The Braincube Model Manager provides powerful tools to create your own Python models and run them on a Braincube edge flow.
Table of Contents
- Prerequisites
- Project Structure
- Braincube Model SDK
- Packaging and Deployment
- Deployment with Model Runner
- Best Practices
- Support
Prerequisites
- Python 3.11+ installed on your development machine
- Access to a development environment (IDE of your choice)
- Docker installed for image creation
- Access to a Docker registry (Docker Hub or private registry)
Project Structure
Your project must contain at minimum:
my-project/
├── main.py # Main file containing your model
├── requirements.txt # Python dependencies
├── Dockerfile # Docker configuration
└── setup.py # Installation configuration (optional)
requirements.txt File
braincube-model-sdk
Braincube Model SDK
The Braincube Model SDK is a Python library enabling asynchronous interaction with the Braincube Edge platform.
Main Components
| Component | Type | Description |
|---|---|---|
Handler |
Class | Base class to inherit for message handling |
run_sdk(handler) |
Function | Starts connection with Edge flow (blocking) |
stop_sdk() |
Function | Stops the SDK (rare usage) |
Methods to Implement
Your class must inherit from Handler and implement these three mandatory methods:
on_init(self, conf: dict)
Called at application startup.
-
Parameter:
conf- configuration dictionary provided by the Model Runner - Usage: Initialize parameters, load models, etc.
on_destroy(self)
Called before application shutdown.
- Usage: Clean up resources, save data, close connections
on_message(self, msg: dict)
Called when a message is received from the Model Runner.
-
Parameter:
msg- dictionary containing the received message - Note: Not mandatory to respond to every message (asynchronous SDK)
Available Methods
send_message(self, msg: dict)
Sends a message to the Model Runner.
-
Parameter:
msg- dictionary containing the message to send - Note: Can be called at any time, even without incoming messages
Complete Example
from braincube_model_sdk import Handler, run_sdk
class MyModel(Handler):
"""Example of a simple calculator model."""
def on_init(self, conf: dict):
"""Initialize the model with configuration."""
self.operator = conf.get('operator', '+')
self.buffer = []
print(f"Model initialized with operator: {self.operator}")
def on_destroy(self):
"""Cleanup before shutdown."""
print(f"Stopping model. {len(self.buffer)} value(s) pending.")
def on_message(self, msg: dict):
"""Process received messages."""
value = msg.get('value')
self.buffer.append(value)
# Process by pairs of values
if len(self.buffer) >= 2:
result = self.calculate(self.buffer[0], self.buffer[1])
self.send_message({'result': result})
self.buffer = []
def calculate(self, a, b):
"""Perform calculation according to configured operator."""
operations = {
'+': lambda x, y: x + y,
'-': lambda x, y: x - y,
'*': lambda x, y: x * y,
'/': lambda x, y: x / y if y != 0 else None
}
operation = operations.get(self.operator)
return operation(a, b) if operation else None
if __name__ == '__main__':
handler = MyModel()
run_sdk(handler)
Packaging and Deployment
Step 1: Create the Dockerfile
Create a Dockerfile file at the root of your project:
FROM python:3.11-bullseye
# Environment variables
ENV PORT=3000
ENV MODEL_MANAGER_PORT=3000
# Working directory configuration
WORKDIR /app
# Copy project files
COPY . /app
# Python version check
RUN python3 --version
# Install dependencies
RUN python3 setup.py install
# Expose port
EXPOSE $MODEL_MANAGER_PORT
# Application entry point
ENTRYPOINT ["python3", "main.py"]
Step 2: Build the Docker Image
From your project root directory, execute:
docker build -t <registry_url>/<image_repo_name>/<project_name>:<tag> .
Examples:
# Docker Hub
docker build -t braincube/my-model:1.0 .
# Private registry
docker build -t registry.mycompany.com/braincube/my-model:1.0 .
# Latest tag
docker build -t braincube/my-model:latest .
Step 3: Verify Image Creation
docker images
Expected output:
REPOSITORY TAG IMAGE ID CREATED SIZE
registry.mycompany.com/braincube/my-model 1.0 abc123def456 10 seconds ago 250MB
Step 4: Tag the Image (Optional)
To add an additional tag to an existing image:
# By image ID
docker tag abc123def456 registry.mycompany.com/braincube/my-model:1.1
# By image name
docker tag registry.mycompany.com/braincube/my-model:1.0 registry.mycompany.com/braincube/my-model:1.1
Step 5: Test the Image Locally (Optional)
docker run -p 8080:3000 registry.mycompany.com/braincube/my-model:1.0
Step 6: Login to Docker Registry
Docker Hub
docker login
Private Registry
docker login registry.mycompany.com
Enter your credentials when prompted.
Step 7: Push the Image to Registry
docker push <registry_url>/<image_repo_name>/<project_name>:<tag>
Examples:
# Specific version
docker push registry.mycompany.com/braincube/my-model:1.0
# Latest version
docker push registry.mycompany.com/braincube/my-model:latest
# All tags at once
docker push registry.mycompany.com/braincube/my-model --all-tags
Step 8: Verify Image Availability
# Try to pull the image
docker pull registry.mycompany.com/braincube/my-model:1.0
Or check your Docker registry's web interface.
Naming Convention
Docker images follow this pattern:
<registry_url>/<image_repo_name>/<project_name>:<tag>
| Component | Description | Example |
|---|---|---|
registry_url |
Docker registry URL | registry.mycompany.com |
image_repo_name |
Organization/client name | braincube |
project_name |
Project name | my-model |
tag |
Model version |
1.0, 1.1, latest
|
Complete examples:
-
braincube/calculator:1.0(Docker Hub) registry.mycompany.com/braincube/predictive-model:2.1registry.mycompany.com/acme/temperature-analyzer:latest
Deployment with Model Runner
Installation on Edge Box
- Access AppsManager
- Select your edge device
- Install the Model Runner application (Edge computing category)
Model Runner Configuration
-
Add the node: Drag and drop the
Model Runnernode into your flow - Configure mandatory parameters:
image Parameter
Full Docker image name with registry URL.
Format: <registry_url>/<image_repo_name>/<project_name>:<tag>
Examples:
braincube/my-model:1.0 # Docker Hub
registry.mycompany.com/braincube/my-model:1.0 # Private registry with tag
registry.mycompany.com/braincube/my-model # Private registry (latest)
configuration Parameter
JSON containing your model parameters (optional but recommended).
Example:
{
"operator": "+",
"threshold": 10,
"model_version": "v2.1"
}
credentials Parameter
Docker registry access credentials (login/password).
Important: These credentials must allow read access to your private registry images.
Connect flows
Link input and output nodes to the Model Runner
How It Works
Processing flow:
Input Flow → Model Runner → Your Python Model → send_message() → Output Flow
The Model Runner:
- ✅ Receives messages via the input flow
- ✅ Transmits data to your Python program (
on_messagemethod) - ✅ Retrieves results via
send_message() - ✅ Sends results to the output flow
Best Practices
Development
| Practice | Description |
|---|---|
| Local Testing | Test your model locally before deployment |
| Error Handling | Implement robust try/except blocks in your methods |
| Structured Logs | Use the logging module for easier debugging |
| Type Hints | Add type annotations to improve readability |
Configuration
- Use the Model Runner's
configurationparameter to make your model configurable - Avoid hardcoding values that might change
- Validate configuration in
on_init()and raise exceptions if necessary
Versioning
Use semantic versioning:
-
MAJOR.MINOR.PATCH(e.g.,1.0.0,1.1.0,2.0.0) - MAJOR: Incompatible changes
- MINOR: New compatible features
- PATCH: Bug fixes
Performance
- Load heavy models in
on_init(), not inon_message() - Use buffers for batch processing if needed
- Monitor your container's memory and CPU usage
Support
For any questions regarding:
- 🔑 Docker image access credentials
- 🏷️ Exact name of your images
- 🐛 Deployment issues
- ⚙️ Model Runner configuration
Contact the Braincube team.