# Model Registry

Discover, search, and manage your deployed models with ViewAI's Model Registry.

## Overview

The Model Registry provides comprehensive capabilities for:

* Listing and discovering deployed models
* Searching and filtering models by various criteria
* Comparing models side-by-side
* Analyzing model metadata and statistics
* Managing model lifecycle
* Tracking deployment history

## ModelRegistry Service

The `ModelRegistry` service provides centralized model management capabilities.

### Initialization

```python
from viewai_client import ViewAIClient

# Initialize client (registry is included)
client = ViewAIClient(api_key="your-api-key")

# Access model registry
registry = client.registry
```

## Listing Models

### List All Models

Get a complete list of deployed models:

```python
# List all models
models = registry.list_models()

print(f"Total models: {len(models)}")

# Display models
for model in models:
    print(f"Model: {model['dashboard_name']}")
    print(f"  ID: {model['dashboard_id']}")
    print(f"  Type: {model['type']}")
    print(f"  Target: {model['target_variable']}")
    print(f"  Created: {model['created_at']}")
    print()
```

### Filtered Listing

Filter models by workspace or project:

```python
# List models in specific workspace
workspace_models = registry.list_models(workspace_id="workspace_123")

# List models in specific project
project_models = registry.list_models(project_id="project_456")

# Limit number of results
recent_models = registry.list_models(limit=10)
```

## Searching Models

### Search by Name

Find models by name pattern:

```python
# Search for models with "churn" in the name
churn_models = registry.search_models(name="churn")

print(f"Found {len(churn_models)} churn models:")
for model in churn_models:
    print(f"  - {model['dashboard_name']}")
```

### Search by Tags

Filter models by tags:

```python
# Search models with specific tags
production_models = registry.search_models(tags=["production"])

# Multiple tags
critical_models = registry.search_models(tags=["production", "critical"])
```

### Search by Date

Find models created within a date range:

```python
from datetime import datetime, timedelta

# Models created in the last 30 days
thirty_days_ago = datetime.now() - timedelta(days=30)
recent_models = registry.search_models(created_after=thirty_days_ago)

# Models created before a specific date
old_cutoff = datetime.now() - timedelta(days=180)
old_models = registry.search_models(created_before=old_cutoff)

# Date range
start_date = datetime(2025, 1, 1)
end_date = datetime(2025, 10, 1)
range_models = registry.search_models(
    created_after=start_date,
    created_before=end_date
)
```

### Combined Search

Combine multiple search criteria:

```python
# Production churn models created in last 60 days
sixty_days_ago = datetime.now() - timedelta(days=60)

models = registry.search_models(
    name="churn",
    tags=["production"],
    created_after=sixty_days_ago
)

print(f"Found {len(models)} matching models")
```

## Getting Model Details

### Get Model by ID

Retrieve a specific model:

```python
# Get model by ID
model = registry.get_model("model_123")

if model:
    print(f"Model: {model['dashboard_name']}")
    print(f"Description: {model.get('dashboard_desc', 'N/A')}")
    print(f"Type: {model['type']}")
    print(f"Target: {model['target_variable']}")
else:
    print("Model not found")
```

### Get Model Metadata

Retrieve comprehensive model metadata:

```python
# Get detailed metadata
metadata = registry.get_model_metadata("model_123")

print("Model Metadata:")
print(f"  ID: {metadata['dashboard_id']}")
print(f"  Name: {metadata['dashboard_name']}")
print(f"  Description: {metadata['dashboard_desc']}")
print(f"  Type: {metadata['type']}")
print(f"  Target: {metadata['target_variable']}")
print(f"  Workspace: {metadata['workspace_id']}")
print(f"  Project: {metadata['project_id']}")
print(f"  Tags: {metadata['tags']}")
print(f"  Status: {metadata['status']}")
print(f"  Created: {metadata['created_at']}")
print(f"  Updated: {metadata['updated_at']}")
```

## Model Comparison

### Compare Multiple Models

Compare models side-by-side:

```python
import pandas as pd

# Compare models
model_ids = ["model_123", "model_456", "model_789"]
comparison_df = registry.compare_models(model_ids)

# Display comparison
print("Model Comparison:")
print(comparison_df[['dashboard_name', 'type', 'target_variable', 'created_at']])

# Export comparison
comparison_df.to_csv('model_comparison.csv', index=False)
```

### Find Similar Models

Find models with the same target variable:

```python
# Find all models predicting churn
churn_models = registry.find_models_by_target("Churn")

print(f"Found {len(churn_models)} churn prediction models:")
for model in churn_models:
    print(f"  - {model['dashboard_name']} ({model['type']})")
```

## Model Analytics

### Get Model Statistics

Analyze your model inventory:

```python
# Get comprehensive statistics
stats = registry.get_model_stats()

print("Model Statistics:")
print(f"  Total models: {stats['total_models']}")

print("\nBy Status:")
for status, count in stats['by_status'].items():
    print(f"  {status}: {count}")

print("\nBy Type:")
for model_type, count in stats['by_type'].items():
    print(f"  {model_type}: {count}")

print("\nBy Workspace:")
for workspace, count in stats['by_workspace'].items():
    print(f"  {workspace}: {count}")
```

### Get Model Summary

Get a comprehensive summary:

```python
# Get summary
summary = registry.get_model_summary()

print("Registry Summary:")
print(f"  Total models: {summary['total_models']}")
print(f"  Pretrained models: {summary['pretrained_count']}")
print(f"  Documented models: {summary['documented_count']}")
print(f"  Starred models: {summary['starred_count']}")
print(f"  Recent models (7 days): {summary['recent_count']}")

print("\nModel Types:")
for model_type, count in summary['by_type'].items():
    print(f"  {model_type}: {count}")

print("\nTarget Variables:")
for target, count in summary['by_target'].items():
    print(f"  {target}: {count}")
```

## Version Management

### List Model Versions

Track different versions of a model:

```python
# List all versions of a model
versions = registry.list_model_versions("Churn Prediction Model")

print(f"Found {len(versions)} versions:")
for version in versions:
    print(f"  Version: {version['dashboard_name']}")
    print(f"    ID: {version['dashboard_id']}")
    print(f"    Created: {version['created_at']}")
    print()
```

### Get Deployment History

Track model deployments over time:

```python
# Get deployment history
history_df = registry.get_deployment_history(days=30)

if not history_df.empty:
    print("Deployment History (Last 30 days):")
    print(history_df[['dashboard_name', 'created_at', 'status']].to_string())

    # Analyze deployment patterns
    deployments_by_day = history_df.groupby(
        history_df['created_at'].dt.date
    ).size()

    print("\nDeployments by day:")
    print(deployments_by_day)
```

## Helper Functions

### Find Models by Name Pattern

```python
# Case-insensitive partial match
models = registry.find_models_by_name("churn")

# Case-sensitive exact match
models = registry.find_models_by_name("Churn Model", case_sensitive=True)

print(f"Found {len(models)} models")
```

### Find Recent Models

```python
# Find models created in last 7 days
recent = registry.find_recent_models(days=7)

# Find models from last 30 days
monthly = registry.find_recent_models(days=30)

print(f"Last 7 days: {len(recent)} models")
print(f"Last 30 days: {len(monthly)} models")
```

### Find Pretrained Models

```python
# Find all pretrained models
pretrained = registry.find_pretrained_models()

print(f"Found {len(pretrained)} pretrained models:")
for model in pretrained:
    print(f"  - {model['dashboard_name']}")
```

### Find Workspace Models

```python
# Find models in current workspace
workspace_models = registry.find_workspace_models()

# Find models in specific workspace
specific_models = registry.find_workspace_models(workspace_id="ws_123")

print(f"Workspace models: {len(workspace_models)}")
```

### Find Documented Models

```python
# Find models with descriptions
documented = registry.find_models_with_descriptions()

print(f"Documented models: {len(documented)}")
for model in documented:
    print(f"  {model['dashboard_name']}: {model['dashboard_desc']}")
```

### Find Starred Models

```python
# Find favorited/starred models
starred = registry.find_starred_models()

print(f"Starred models: {len(starred)}")
for model in starred:
    print(f"  - {model['dashboard_name']}")
```

## Model Lifecycle

### Get Model by Name

```python
# Get specific model by exact name
model = registry.get_model_by_name("Customer Churn Model", exact_match=True)

# Get model by partial name match
model = registry.get_model_by_name("churn", exact_match=False)

if model:
    print(f"Found: {model['dashboard_name']}")
```

### List Model Names

```python
# Get all model names
model_names = registry.list_model_names()

print("Available models:")
for name in model_names:
    print(f"  - {name}")
```

### List Target Variables

```python
# Get all unique target variables
targets = registry.list_target_variables()

print("Target variables in use:")
for target in targets:
    print(f"  - {target}")
```

### Delete Model

```python
# Delete a model
success = registry.delete_model("model_123")

if success:
    print("Model deleted successfully")
else:
    print("Failed to delete model")
```

## Advanced Use Cases

### Model Discovery Workflow

```python
def discover_models_workflow(registry):
    """Complete model discovery workflow."""

    # 1. List all models
    all_models = registry.list_models()
    print(f"Total models: {len(all_models)}")

    # 2. Get statistics
    stats = registry.get_model_stats()
    print(f"\nModel types: {stats['by_type']}")

    # 3. Find production models
    production = registry.search_models(tags=["production"])
    print(f"\nProduction models: {len(production)}")

    # 4. Find recent deployments
    recent = registry.find_recent_models(days=7)
    print(f"Recent deployments: {len(recent)}")

    # 5. Check for undocumented models
    all_count = len(all_models)
    documented_count = len(registry.find_models_with_descriptions())
    undocumented = all_count - documented_count

    print(f"\nDocumentation status:")
    print(f"  Documented: {documented_count}")
    print(f"  Undocumented: {undocumented}")

# Run workflow
discover_models_workflow(registry)
```

### Model Comparison Report

```python
def generate_comparison_report(registry, model_ids):
    """Generate detailed comparison report."""

    # Compare models
    comparison_df = registry.compare_models(model_ids)

    if comparison_df.empty:
        print("No models found for comparison")
        return

    print("=" * 80)
    print("MODEL COMPARISON REPORT")
    print("=" * 80)

    # Basic info
    print("\nBasic Information:")
    print(comparison_df[['dashboard_name', 'type', 'target_variable']])

    # Metadata
    print("\nMetadata:")
    print(comparison_df[['created_at', 'updated_at', 'status']])

    # Tags
    print("\nTags:")
    for _, row in comparison_df.iterrows():
        print(f"  {row['dashboard_name']}: {row.get('tags', [])}")

    # Statistics
    print("\nStatistics:")
    print(f"  Models compared: {len(comparison_df)}")
    print(f"  Types: {comparison_df['type'].unique()}")
    print(f"  Targets: {comparison_df['target_variable'].unique()}")

    return comparison_df

# Generate report
model_ids = ["model_123", "model_456", "model_789"]
report_df = generate_comparison_report(registry, model_ids)
```

### Model Inventory Audit

```python
def audit_model_inventory(registry):
    """Audit model inventory for compliance."""

    print("MODEL INVENTORY AUDIT")
    print("=" * 80)

    # Get all models
    models = registry.list_models()
    summary = registry.get_model_summary()

    print(f"\nTotal Models: {len(models)}")

    # Check documentation
    documented = registry.find_models_with_descriptions()
    doc_rate = (len(documented) / len(models)) * 100 if models else 0

    print(f"\nDocumentation:")
    print(f"  Documented: {len(documented)} ({doc_rate:.1f}%)")
    print(f"  Missing documentation: {len(models) - len(documented)}")

    # Check recent activity
    recent_7d = registry.find_recent_models(days=7)
    recent_30d = registry.find_recent_models(days=30)

    print(f"\nRecent Activity:")
    print(f"  Last 7 days: {len(recent_7d)} deployments")
    print(f"  Last 30 days: {len(recent_30d)} deployments")

    # Check for stale models
    old_cutoff = datetime.now() - timedelta(days=180)
    old_models = [
        m for m in models
        if datetime.fromisoformat(m['created_at'].replace('Z', '+00:00')) < old_cutoff
    ]

    print(f"\nStale Models (>180 days):")
    print(f"  Count: {len(old_models)}")

    # Type distribution
    print(f"\nModel Type Distribution:")
    for model_type, count in summary['by_type'].items():
        percentage = (count / len(models)) * 100
        print(f"  {model_type}: {count} ({percentage:.1f}%)")

    # Recommendations
    print(f"\nRecommendations:")
    if doc_rate < 80:
        print("  - Add documentation to undocumented models")
    if len(old_models) > 0:
        print(f"  - Review {len(old_models)} stale models for archival")
    if len(recent_7d) == 0:
        print("  - No recent deployments detected")

# Run audit
audit_model_inventory(registry)
```

### Model Health Dashboard

```python
def create_model_dashboard(registry):
    """Create a model health dashboard."""

    models = registry.list_models()
    summary = registry.get_model_summary()

    dashboard = {
        'overview': {
            'total_models': len(models),
            'pretrained': summary['pretrained_count'],
            'documented': summary['documented_count'],
            'starred': summary['starred_count']
        },
        'recent_activity': {
            'last_7_days': len(registry.find_recent_models(days=7)),
            'last_30_days': len(registry.find_recent_models(days=30))
        },
        'distribution': {
            'by_type': summary['by_type'],
            'by_target': summary['by_target']
        }
    }

    # Print dashboard
    print("MODEL HEALTH DASHBOARD")
    print("=" * 80)

    print("\nOverview:")
    for key, value in dashboard['overview'].items():
        print(f"  {key.replace('_', ' ').title()}: {value}")

    print("\nRecent Activity:")
    for key, value in dashboard['recent_activity'].items():
        print(f"  {key.replace('_', ' ').title()}: {value}")

    print("\nDistribution by Type:")
    for model_type, count in dashboard['distribution']['by_type'].items():
        print(f"  {model_type}: {count}")

    print("\nDistribution by Target:")
    for target, count in dashboard['distribution']['by_target'].items():
        print(f"  {target}: {count}")

    return dashboard

# Create dashboard
dashboard = create_model_dashboard(registry)
```

## Complete Example

```python
from viewai_client import ViewAIClient
from datetime import datetime, timedelta
import pandas as pd

# Initialize client
client = ViewAIClient(api_key="your-api-key")
registry = client.registry

# 1. List all models
print("1. Listing all models...")
models = registry.list_models()
print(f"   Found {len(models)} models")

# 2. Search for specific models
print("\n2. Searching for churn models...")
churn_models = registry.search_models(name="churn")
print(f"   Found {len(churn_models)} churn models")

# 3. Get model details
if models:
    print("\n3. Getting details for first model...")
    first_model = models[0]
    metadata = registry.get_model_metadata(first_model['dashboard_id'])
    print(f"   Model: {metadata['dashboard_name']}")
    print(f"   Type: {metadata['type']}")

# 4. Compare models
if len(models) >= 2:
    print("\n4. Comparing models...")
    model_ids = [m['dashboard_id'] for m in models[:2]]
    comparison = registry.compare_models(model_ids)
    print(f"   Compared {len(comparison)} models")

# 5. Get statistics
print("\n5. Getting model statistics...")
stats = registry.get_model_stats()
print(f"   Total: {stats['total_models']}")
print(f"   Types: {stats['by_type']}")

# 6. Find recent models
print("\n6. Finding recent models...")
recent = registry.find_recent_models(days=30)
print(f"   Found {len(recent)} models from last 30 days")

# 7. Get model summary
print("\n7. Getting model summary...")
summary = registry.get_model_summary()
print(f"   Documented: {summary['documented_count']}")
print(f"   Starred: {summary['starred_count']}")

print("\n✓ Model registry operations completed")
```

## Best Practices

{% stepper %}
{% step %}

### Regular Audits

Audit your model inventory regularly.
{% endstep %}

{% step %}

### Documentation

Always add descriptions to deployed models.
{% endstep %}

{% step %}

### Tagging

Use a consistent tagging strategy for organization.
{% endstep %}

{% step %}

### Version Tracking

Track model versions for reproducibility.
{% endstep %}

{% step %}

### Cleanup

Archive or delete outdated models.
{% endstep %}

{% step %}

### Monitoring

Monitor deployment frequency and patterns.
{% endstep %}

{% step %}

### Comparison

Compare models before promoting to production.
{% endstep %}

{% step %}

### Metadata

Maintain comprehensive metadata for all models.
{% endstep %}

{% step %}

### Search

Use tags and naming conventions for easy discovery.
{% endstep %}

{% step %}

### Reporting

Generate regular inventory reports.
{% endstep %}
{% endstepper %}

## Troubleshooting

### No Models Found

```python
models = registry.list_models()

if not models:
    print("No models found. Check:")
    print("1. API key permissions")
    print("2. Workspace access")
    print("3. Model deployment status")
```

### Search Returns Empty

```python
results = registry.search_models(name="churn")

if not results:
    print("No results. Try:")
    print("1. Case-insensitive search")
    print("2. Partial name match")
    print("3. Check model names with list_model_names()")
```

### Model Not Found by ID

```python
model = registry.get_model("model_123")

if not model:
    print("Model not found. Verify:")
    print("1. Model ID is correct")
    print("2. Model exists in workspace")
    print("3. Model hasn't been deleted")

    # List all model IDs
    all_models = registry.list_models()
    print(f"\nAvailable model IDs:")
    for m in all_models:
        print(f"  - {m['dashboard_id']}")
```

## Next Steps

* Learn about [Version Management](broken://pages/5a50d3e7ba93df86f5b78caac6ee1d6e125d48aa)
* Explore [Performance Optimization](broken://pages/3f0ef7ae608cc5fded6a0f6a239b44d0eebdec0b)
* Review [Best Practices](broken://pages/4dd0782dc2b77e549c39957bc7bbc2101bd78d21)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.viewai.ca/mlops/model-registry.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
