ModelLens

PYTHON SDK

ModelLens SDK

Integrate model explainability into your Python workflows. Upload models, run analysis, and chat with Perun programmatically.

Installation

pip install modellens

Requires Python 3.10+. The only dependency is httpx.

Quick start

from weight2text_sdk import W2TClient

client = W2TClient("https://modellens-api.azurewebsites.net")
client.login("your-username", "your-password")

# List your models
models = client.list_models()
for m in models:
    print(f"{m.name}{m.task_type} ({m.exploration_status})")

# Chat with a model
response = client.chat(model_id, "Which features matter most?")
print(response.answer)

Authentication

Three ways to authenticate:

Username & password

client = W2TClient(base_url)
client.login("username", "password")

API key (recommended for automation)

client = W2TClient(base_url, api_key="ml_sk_...")

Generate API keys from your account settings. Requires Pro plan or above.

Pre-existing JWT token

client = W2TClient(base_url, token="eyJ...")

Upload & explore a model

model = client.upload_model(
    model_file="my_classifier.pt",
    name="Fraud Detector v2",
    feature_names=["amount", "hour", "merchant_risk", "velocity"],
    class_names=["legitimate", "fraud"],
    task_type="classification",
    sensitive_features=["age", "gender"],   # triggers fairness analysis
    description="Detects fraudulent credit card transactions",
)

# Wait for automatic exploration to finish
status = client.wait_for_exploration(model.id)
print(f"Exploration: {status.status}")

# Read the generated knowledge card
card = client.get_knowledge_card(model.id)
print(card)

Chat with your model

# Synchronous chat
response = client.chat(model.id, "Why does the model flag this transaction?",
    current_features={"amount": 4500, "hour": 3, "merchant_risk": 0.9, "velocity": 12})
print(response.answer)

# Streaming chat
for event in client.chat_stream(model.id, "/summary"):
    if event.type == "text_delta":
        print(event.delta, end="", flush=True)
    elif event.type == "tool_call":
        print(f"\n  [Tool: {event.name}]")
    elif event.type == "done":
        print(f"\n\nDone — {event.num_tool_calls} tool calls")

Built-in slash commands: /summary /features /rules /trust /risk /fairness

Predictions & analysis

# Batch predictions from CSV
result = client.predict_batch(model.id, "test_data.csv")
for row in result.predictions:
    print(f"{row.predicted_class} ({row.confidence:.0%})")

# Feature trends — how does prediction change as 'amount' varies?
trends = client.trends(model.id, "amount", min_val=0, max_val=10000, n_points=50)

# Counterfactual — what needs to change to flip the prediction?
cf = client.counterfactual(model.id,
    features={"amount": 4500, "hour": 3, "merchant_risk": 0.9, "velocity": 12},
    target_class="legitimate")
for change in cf.changes:
    print(f"  {change.feature}: {change.from_value} -> {change.to_value}")

# Deep analysis — permutation importance, PDPs, scenarios
client.start_deep_analysis(model.id)
summary = client.wait_for_deep_analysis(model.id)
for feat in summary.top_features[:5]:
    print(f"  {feat['feature']}: {feat['importance_mean']:.4f}")

Advanced analysis

spectral_analysis()

SVD-based weight matrix health metrics — stable rank, signal rank, neural collapse index

symbolic_rules()

Extract human-readable if-then decision rules via surrogate decision tree

model_genome()

7-component Weight DNA Fingerprint — a unique behavioural signature of your model

mechanistic_trace()

Layer-by-layer feature flow showing which neurons activate for a given input

h_statistic()

Friedman H-statistic for pairwise feature interactions

weight_diff()

Compare two model versions — weight changes, prediction drift, and summary

tcav_scores()

Concept activation vectors — how sensitive are hidden layers to high-level concepts?

tabcheck()

Automated behavioural test suite — generates and runs edge case tests

Error handling

from weight2text_sdk import (
    W2TClient, W2TError, AuthError, NotFoundError,
    RateLimitError, QuotaExceededError
)

try:
    response = client.chat(model_id, "Explain this prediction")
except AuthError:
    print("Not authenticated — call client.login() first")
except QuotaExceededError as e:
    print(f"Monthly chat limit reached. Resets: {e.detail}")
except RateLimitError:
    print("Too many requests — slow down")
except NotFoundError:
    print("Model not found")
except W2TError as e:
    print(f"API error {e.status_code}: {e}")

Context manager

with W2TClient(base_url, api_key="ml_sk_...") as client:
    models = client.list_models()
    for m in models:
        card = client.get_knowledge_card(m.id)
        print(f"--- {m.name} ---")
        print(card[:200])
# Connection pool automatically cleaned up

Requirements

Python 3.10+

Tested on 3.10, 3.11, 3.12

httpx

Only runtime dependency

Pro plan or above

API access requires a paid plan

View on GitHub

Found a bug? Open an issue