Quickstart
Initialize the Client
First, import and initialize the ViewAI client with your API key:
from viewai_client import ViewAIClient
# Initialize with API key
client = ViewAIClient(api_key="your-api-key-here")
# Or use environment variable
import os
client = ViewAIClient(api_key=os.getenv("VIEWAI_API_KEY"))Hint — Verify Connection:
# Check if the API is reachable
health = client.health.check_connection()
if health.healthy:
print(f"✓ Connected successfully ({health.response_time_ms:.0f}ms)")
else:
print(f"✗ Connection failed: {health.message}")Prepare Your Data
The SDK works with pandas DataFrames. Example to create a sample dataset:
import pandas as pd
import numpy as np
# Create sample customer churn dataset
np.random.seed(42)
n_samples = 1000
data = {
'age': np.random.randint(18, 70, n_samples),
'income': np.random.randint(30000, 150000, n_samples),
'tenure_months': np.random.randint(1, 60, n_samples),
'monthly_charges': np.random.uniform(20, 200, n_samples),
'total_purchases': np.random.randint(0, 50, n_samples),
'support_calls': np.random.randint(0, 10, n_samples),
'contract_type': np.random.choice(['monthly', 'annual', 'biannual'], n_samples),
'payment_method': np.random.choice(['credit', 'debit', 'paypal'], n_samples),
# Target variable
'churn': np.random.choice([0, 1], n_samples, p=[0.7, 0.3])
}
df = pd.DataFrame(data)
print(f"Dataset shape: {df.shape}")
print(f"Churn rate: {df['churn'].mean():.2%}")Set Up Workspace
Workspaces organize your models. Get the default workspace or list accessible workspaces:
# Get default workspace
workspace = client.retrieve_default_workspace()
print(f"Using workspace: {workspace.workspace_name}")
# Or list all accessible workspaces
workspaces = client.list_accessible_workspaces()
for ws in workspaces:
print(f" - {ws.workspace_name} (ID: {ws.workspace_id})")
# Set current workspace
client.set_current_workspace(workspace)Train a Model
Initiate a training job on the ViewAI platform:
# Initiate training job
print("Starting model training...")
training_job = client.training_service.initiate_training_job(
dataset=df,
target_column='churn',
workspace=workspace,
model_name='Customer Churn Predictor',
description='Predicts customer churn based on usage patterns',
wait_for_completion=True # Wait for training to complete
)
if training_job and 'completed' in training_job.status:
print(f"✓ Training completed!")
print(f" Model ID: {training_job.job_id}")
print(f" Dashboard: {training_job.dashboard_url}")
model_id = training_job.job_id
else:
print("✗ Training failed")Training Output example:
Training Progress: 100%|██████████| 30/30 [02:15<00:00]
✓ Training completed! View model at: https://app.viewai.ca/dashboard/model-123Make Predictions
Single prediction example:
# Prepare test data (single customer)
customer_data = {
'age': 35,
'income': 75000,
'tenure_months': 24,
'monthly_charges': 85.50,
'total_purchases': 15,
'support_calls': 2,
'contract_type': 'monthly',
'payment_method': 'credit'
}
# Make prediction
prediction = client.prediction_service.execute_single_point_prediction(
data=customer_data,
model_id=model_id
)
if prediction:
print("Prediction results:")
print(f" Raw prediction: {prediction.get_raw_prediction()}")
print(f" Probabilities: {prediction.get_probabilities()}")Output example:
Prediction results:
Raw prediction: {'predicted_churn': 1, 'probability_0': 0.32, 'probability_1': 0.68}
Probabilities: {'probability_0': 0.32, 'probability_1': 0.68}Batch prediction example:
# Prepare batch data (multiple customers)
batch_customers = [
{'age': 25, 'income': 45000, 'tenure_months': 6, ...},
{'age': 50, 'income': 95000, 'tenure_months': 48, ...},
{'age': 33, 'income': 67000, 'tenure_months': 18, ...}
]
# Or use a DataFrame
batch_df = df.drop('churn', axis=1).head(10)
# Make batch prediction
batch_job = client.prediction_service.execute_batch_prediction(
data=batch_df,
model_id=model_id,
wait_for_completion=True
)
if batch_job and batch_job.status == 'completed':
print(f"✓ Batch prediction completed!")
print(f" Job ID: {batch_job.job_id}")
print(f" View results: {batch_job.dashboard_url}")Monitor Your Model
Inspect registry and run diagnostics:
# Get model from registry
models = client.registry.list_models()
our_model = next((m for m in models if m.get('dashboard_id') == model_id), None)
if our_model:
print(f"Model: {our_model.get('dashboard_name')}")
print(f" Type: {our_model.get('type')}")
print(f" Status: {our_model.get('status')}")
print(f" Created: {our_model.get('created_at')}")
# Run diagnostics
diagnostics = client.health.run_diagnostics()
for check_name, result in diagnostics.items():
status = '✓' if result.healthy else '✗'
print(f"{status} {check_name}: {result.message}")Complete Example
from viewai_client import ViewAIClient
import pandas as pd
import numpy as np
import os
# Initialize client
client = ViewAIClient(api_key=os.getenv("VIEWAI_API_KEY"))
# Verify connection
health = client.health.check_connection()
if not health.healthy:
print("Failed to connect to ViewAI API")
exit(1)
# Create sample data
np.random.seed(42)
df = pd.DataFrame({
'age': np.random.randint(18, 70, 1000),
'income': np.random.randint(30000, 150000, 1000),
'tenure_months': np.random.randint(1, 60, 1000),
'churn': np.random.choice([0, 1], 1000, p=[0.7, 0.3])
})
# Get workspace
workspace = client.retrieve_default_workspace()
client.set_current_workspace(workspace)
# Train model
print("Training model...")
training_job = client.training_service.initiate_training_job(
dataset=df,
target_column='churn',
workspace=workspace,
model_name='Quick Start Model',
wait_for_completion=True
)
if not training_job or 'completed' not in training_job.status:
print("Training failed!")
exit(1)
model_id = training_job.job_id
print(f"Model trained successfully: {model_id}")
# Make prediction
test_data = {
'age': 35,
'income': 75000,
'tenure_months': 24
}
prediction = client.prediction_service.execute_single_point_prediction(
data=test_data,
model_id=model_id
)
print(f"Prediction: {prediction.get_raw_prediction()}")
print("✓ Quick start completed successfully!")Common Patterns
Train and Deploy
Using Context Manager
Configuration Object
Next Steps
Learn more and try advanced features:
📘 Core Concepts - Understand workspaces, projects, and models
🔐 Authentication - Secure API key management
🎯 Predictions Guide - Advanced prediction patterns
Try advanced features:
🚀 Model Deployment
📊 Batch Processing
🏥 Health Monitoring
Examples:
💼 Complete Workflows
🎓 Training Examples
🔮 Prediction Examples
Troubleshooting
Best Practices
Always check connection before operations
Use environment variables for API keys
Handle errors gracefully with try-except blocks
Set appropriate timeouts for long operations
Monitor your models regularly
Use workspaces to organize projects
Validate data before predictions
Clean up resources with context managers
Support
Need help?
Ready to build production ML pipelines? Check out the Complete Workflows guide!
Was this helpful?