Claude Code for Evidently: ML Model Monitoring — Claude Skills 360 Blog
Blog / AI / Claude Code for Evidently: ML Model Monitoring
AI

Claude Code for Evidently: ML Model Monitoring

Published: September 9, 2027
Read time: 5 min read
By: Claude Skills 360

Evidently monitors ML models and data quality in production. pip install evidently. Report(metrics=[DataDriftPreset(), DataQualityPreset(), TargetDriftPreset()]). report.run(reference_data=train_df, current_data=prod_df, column_mapping=ColumnMapping(target="churned", prediction="score", numerical_features=[...])). report.save_html("report.html"). report.as_dict() for programmatic parsing. Tests: suite = TestSuite(tests=[TestNumberOfColumnsWithMissingValues(lt=2), TestShareOfDrifted Features(lt=0.3), TestColumnDrift(column_name="amount_usd"), TestValueRange(column_name="amount_usd", gte=0.0)]). suite.run(...). suite.as_dict()["summary"]["all_passed"]. Individual metrics: DatasetDriftMetric(), ColumnDriftMetric(column_name="age"), DatasetMissingValuesMetric(), ColumnSummaryMetric(column_name="amount_usd"), ClassificationQualityMetric(), RegressionQualityMetric(). ColumnMapping: ColumnMapping(target=None, numerical_features=[], categorical_features=[], datetime_features=[], prediction="prediction"). Snapshots for continuous monitoring: Snapshot.from_report(report, timestamp=datetime.now()). WorkspaceView stores snapshots and renders monitoring panels. workspace = Workspace.create("./monitoring_workspace"), workspace.add_snapshot("churn_model", snapshot). ws.search_snapshots(project_id, timestamp_start, timestamp_end). MLflow integration: log_metric("drift_share", report.as_dict()["metrics"][0]["result"]["share_of_drifted_columns"]). Grafana: JSON metrics export from report dict to push to Prometheus pushgateway. Claude Code generates Evidently reports, test suites, monitoring snapshots, column mappings, and CI/CD drift gates.

CLAUDE.md for Evidently

## Evidently Stack
- Version: evidently >= 0.4
- Report: Report(metrics=[DataDriftPreset(), DataQualityPreset()]) → run(reference, current, column_mapping)
- Tests: TestSuite(tests=[TestColumnDrift(), TestShareOfDriftedFeatures(lt=0.3)])
- Column mapping: ColumnMapping(target, prediction, numerical_features, categorical_features)
- Save: report.save_html("report.html") or report.as_dict() for JSON
- Monitoring: workspace.add_snapshot(project_name, Snapshot.from_report(report, timestamp))
- CI gate: suite.as_dict()["summary"]["all_passed"] → sys.exit(1 if failed)

Reports and Test Suites

# monitoring/evidently_monitor.py — complete Evidently monitoring setup
from __future__ import annotations
import json
import sys
from datetime import datetime
from pathlib import Path
from typing import Optional

import pandas as pd
from evidently import ColumnMapping
from evidently.metrics import (
    ColumnDriftMetric,
    ColumnSummaryMetric,
    DatasetDriftMetric,
    DatasetMissingValuesMetric,
    ClassificationQualityMetric,
    ClassificationClassBalance,
)
from evidently.metric_preset import (
    DataDriftPreset,
    DataQualityPreset,
    TargetDriftPreset,
    ClassificationPreset,
)
from evidently.report import Report
from evidently.test_preset import (
    DataDriftTestPreset,
    DataQualityTestPreset,
    DataStabilityTestPreset,
)
from evidently.tests import (
    TestColumnDrift,
    TestShareOfDriftedColumns,
    TestNumberOfMissingValues,
    TestNumberOfDuplicatedRows,
    TestValueRange,
    TestColumnValueMean,
    TestHighlyCorrelatedColumns,
)
from evidently.test_suite import TestSuite

FEATURE_COLS     = ["age", "tenure_days", "monthly_spend", "support_tickets", "last_login_days"]
CATEGORICAL_COLS = ["status", "plan"]
TARGET_COL       = "churned"
PREDICTION_COL   = "churn_score"


def build_column_mapping(with_prediction: bool = True) -> ColumnMapping:
    return ColumnMapping(
        target=TARGET_COL if with_prediction else None,
        prediction=PREDICTION_COL if with_prediction else None,
        numerical_features=FEATURE_COLS,
        categorical_features=CATEGORICAL_COLS,
        datetime_features=[],
    )


# ── Data Quality Report ───────────────────────────────────────────────────────

def run_data_quality_report(
    reference_data: pd.DataFrame,
    current_data:   pd.DataFrame,
    output_dir:     str = "reports",
) -> dict:
    """Generate data quality and drift report."""
    Path(output_dir).mkdir(exist_ok=True)
    mapping = build_column_mapping(with_prediction=False)

    report = Report(metrics=[
        DataQualityPreset(),
        DataDriftPreset(num_stattest="ks", cat_stattest="psi", stattest_threshold=0.05),
        DatasetDriftMetric(),
        DatasetMissingValuesMetric(),
        # Per-column summaries for key features
        *[ColumnSummaryMetric(column_name=col) for col in FEATURE_COLS[:3]],
        *[ColumnDriftMetric(column_name=col) for col in FEATURE_COLS],
    ])

    report.run(
        reference_data=reference_data,
        current_data=current_data,
        column_mapping=mapping,
    )

    ts   = datetime.now().strftime("%Y%m%d_%H%M%S")
    html_path = f"{output_dir}/data_quality_{ts}.html"
    json_path = f"{output_dir}/data_quality_{ts}.json"
    report.save_html(html_path)

    result = report.as_dict()
    with open(json_path, "w") as f:
        json.dump(result, f, indent=2, default=str)

    print(f"Report saved: {html_path}")
    return result


# ── Model Performance Report ──────────────────────────────────────────────────

def run_model_report(
    reference_data: pd.DataFrame,
    current_data:   pd.DataFrame,
    output_dir:     str = "reports",
) -> dict:
    """Generate model performance and target drift report."""
    Path(output_dir).mkdir(exist_ok=True)
    mapping = build_column_mapping(with_prediction=True)

    report = Report(metrics=[
        ClassificationPreset(),
        TargetDriftPreset(),
        ClassificationQualityMetric(),
        ClassificationClassBalance(),
    ])

    report.run(
        reference_data=reference_data,
        current_data=current_data,
        column_mapping=mapping,
    )

    ts = datetime.now().strftime("%Y%m%d_%H%M%S")
    html_path = f"{output_dir}/model_report_{ts}.html"
    report.save_html(html_path)
    print(f"Model report saved: {html_path}")
    return report.as_dict()


# ── Test Suite (CI/CD gate) ───────────────────────────────────────────────────

def run_test_suite(
    reference_data: pd.DataFrame,
    current_data:   pd.DataFrame,
    drift_threshold: float = 0.3,
) -> tuple[bool, dict]:
    """Run test suite — returns (passed, results_dict)."""
    mapping = build_column_mapping(with_prediction=False)

    suite = TestSuite(tests=[
        # Stability
        DataStabilityTestPreset(),
        # Drift
        TestShareOfDriftedColumns(lt=drift_threshold),
        *[TestColumnDrift(column_name=col) for col in FEATURE_COLS],
        # Completeness
        TestNumberOfMissingValues(lt=100),
        TestNumberOfDuplicatedRows(lt=0.01),
        # Range checks
        TestValueRange(column_name="age",          gte=18.0,  lte=120.0),
        TestValueRange(column_name="monthly_spend", gte=0.0,   lte=50000.0),
        TestValueRange(column_name="tenure_days",   gte=0.0),
        # Distribution checks
        TestColumnValueMean(column_name="monthly_spend", gte=20.0, lte=2000.0),
    ])

    suite.run(
        reference_data=reference_data,
        current_data=current_data,
        column_mapping=mapping,
    )

    result  = suite.as_dict()
    passed  = result["summary"]["all_passed"]
    n_fail  = result["summary"]["failed_tests"]
    n_total = result["summary"]["total_tests"]

    status = "PASSED" if passed else "FAILED"
    print(f"Test suite {status}: {n_total - n_fail}/{n_total} tests passed")

    if not passed:
        for test in result["tests"]:
            if test["status"] == "FAIL":
                print(f"  FAIL: {test['name']}{test.get('description', '')}")

    return passed, result


# ── Production monitoring with snapshots ─────────────────────────────────────

def record_monitoring_snapshot(
    reference_data:  pd.DataFrame,
    current_data:    pd.DataFrame,
    workspace_path:  str = "./monitoring_workspace",
    project_name:    str = "churn-model",
) -> None:
    """Store a timestamped snapshot to the ZenML/Evidently workspace."""
    from evidently.ui.workspace import Workspace
    from evidently.ui.base import Snapshot

    workspace = Workspace.create(workspace_path)

    report = Report(metrics=[
        DataDriftPreset(),
        ClassificationPreset(),
        DataQualityPreset(),
    ])
    report.run(
        reference_data=reference_data,
        current_data=current_data,
        column_mapping=build_column_mapping(with_prediction=True),
    )

    snapshot  = Snapshot.from_report(report, timestamp=datetime.now())
    workspace.add_snapshot(project_name, snapshot)
    print(f"Snapshot recorded for project '{project_name}'")


# ── Prometheus metrics export ─────────────────────────────────────────────────

def export_prometheus_metrics(report_dict: dict, model_name: str = "churn") -> str:
    """Format Evidently results as Prometheus text exposition."""
    lines = []
    metrics_section = report_dict.get("metrics", [])

    for metric in metrics_section:
        result = metric.get("result", {})
        mtype  = metric.get("metric", "unknown").lower().replace(".", "_")

        if "drift_detected" in result:
            val = 1 if result["drift_detected"] else 0
            lines.append(f'evidently_drift_detected{{model="{model_name}",metric="{mtype}"}} {val}')

        if "share_of_drifted_columns" in result:
            val = result["share_of_drifted_columns"]
            lines.append(f'evidently_drift_share{{model="{model_name}"}} {val}')

        if "current" in result and "missing_values_share" in (result.get("current") or {}):
            val = result["current"]["missing_values_share"]
            lines.append(f'evidently_missing_values_share{{model="{model_name}"}} {val}')

    return "\n".join(lines)


# ── CLI entry point ───────────────────────────────────────────────────────────

if __name__ == "__main__":
    import argparse

    parser = argparse.ArgumentParser()
    parser.add_argument("--reference", required=True)
    parser.add_argument("--current",   required=True)
    parser.add_argument("--mode",      choices=["report", "test", "snapshot"], default="test")
    args = parser.parse_args()

    ref = pd.read_csv(args.reference)
    cur = pd.read_csv(args.current)

    if args.mode == "report":
        run_data_quality_report(ref, cur)
    elif args.mode == "test":
        passed, _ = run_test_suite(ref, cur)
        sys.exit(0 if passed else 1)
    elif args.mode == "snapshot":
        record_monitoring_snapshot(ref, cur)

GitHub Actions Integration

# .github/workflows/model-monitoring.yml — daily drift detection
name: Model Drift Monitor

on:
  schedule:
    - cron: "0 8 * * *"   # daily at 8am UTC
  workflow_dispatch:

jobs:
  drift-check:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - uses: actions/setup-python@v5
        with: { python-version: "3.11" }

      - run: pip install evidently pandas boto3

      - name: Download reference + current data from S3
        env:
          AWS_ACCESS_KEY_ID:     ${{ secrets.AWS_ACCESS_KEY_ID }}
          AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
        run: |
          aws s3 cp s3://my-bucket/reference/train.csv reference.csv
          aws s3 cp s3://my-bucket/production/scoring_$(date +%Y%m%d).csv current.csv

      - name: Run Evidently test suite
        run: |
          python monitoring/evidently_monitor.py \
            --reference reference.csv \
            --current   current.csv \
            --mode      test

      - name: Alert on drift
        if: failure()
        uses: actions/github-script@v7
        with:
          script: |
            github.rest.issues.create({
              owner: context.repo.owner,
              repo:  context.repo.repo,
              title: `Data drift detected — ${new Date().toISOString().slice(0,10)}`,
              body:  "Evidently test suite failed. Check the monitoring dashboard.",
              labels: ["ml-monitoring", "data-drift"],
            })

For the NannyML alternative when needing confidence-based performance estimation on unlabeled production data using CBPE and DLE methods that track model performance even when ground truth labels are delayed — NannyML’s unique estimation approach is superior when labels arrive days or weeks later while Evidently requires actual labels for performance monitoring but provides richer data quality and drift visualization with its Report and TestSuite API. For the Arize Phoenix alternative when needing a unified observability platform covering LLM traces, embeddings, and traditional ML model drift in a single UI with vector similarity search over traces — Phoenix excels for LLM-heavy workloads while Evidently is battle-tested for classical ML monitoring with tabular data drift detection, rich HTML reports, and the Workspace snapshot API for team-visible production dashboards. The Claude Skills 360 bundle includes Evidently skill sets covering data quality reports, drift test suites, monitoring snapshots, Prometheus export, and GitHub Actions drift gates. Start with the free tier to try ML monitoring generation.

Keep Reading

AI

Claude Code for email.contentmanager: Python Email Content Accessors

Read and write EmailMessage body content with Python's email.contentmanager module and Claude Code — email contentmanager ContentManager for the class that maps content types to get and set handler functions allowing EmailMessage to support get_content and set_content with type-specific behaviour, email contentmanager raw_data_manager for the ContentManager instance that handles raw bytes and str payloads without any conversion, email contentmanager content_manager for the standard ContentManager instance used by email.policy.default that intelligently handles text plain text html multipart and binary content types, email contentmanager get_content_text for the handler that returns the decoded text payload of a text-star message part as a str, email contentmanager get_content_binary for the handler that returns the raw decoded bytes payload of a non-text message part, email contentmanager get_data_manager for the get-handler lookup used by EmailMessage get_content to find the right reader function for the content type, email contentmanager set_content text for the handler that creates and sets a text part correctly choosing charset and transfer encoding, email contentmanager set_content bytes for the handler that creates and sets a binary part with base64 encoding and optional filename Content-Disposition, email contentmanager EmailMessage get_content for the method that reads the message body using the registered content manager handlers, email contentmanager EmailMessage set_content for the method that sets the message body and MIME headers in one call, email contentmanager EmailMessage make_alternative make_mixed make_related for the methods that convert a simple message into a multipart container, email contentmanager EmailMessage add_attachment for the method that attaches a file or bytes to a multipart message, and email contentmanager integration with email.message and email.policy and email.mime and io for building high-level email readers attachment extractors text body accessors HTML readers and policy-aware MIME construction pipelines.

5 min read Feb 12, 2029
AI

Claude Code for email.charset: Python Email Charset Encoding

Control header and body encoding for international email with Python's email.charset module and Claude Code — email charset Charset for the class that wraps a character set name with the encoding rules for header encoding and body encoding describing how to encode text for that charset in email messages, email charset Charset header_encoding for the attribute specifying whether headers using this charset should use QP quoted-printable encoding BASE64 encoding or no encoding, email charset Charset body_encoding for the attribute specifying the Content-Transfer-Encoding to use for message bodies in this charset such as QP or BASE64, email charset Charset output_codec for the attribute giving the Python codec name used to encode the string to bytes for the wire format, email charset Charset input_codec for the attribute giving the Python codec name used to decode incoming bytes to str, email charset Charset get_output_charset for returning the output charset name, email charset Charset header_encode for encoding a header string using the charset's header_encoding method, email charset Charset body_encode for encoding body content using the charset's body_encoding, email charset Charset convert for converting a string from the input_codec to the output_codec, email charset add_charset for registering a new charset with custom encoding rules in the global charset registry, email charset add_alias for adding an alias name that maps to an existing registered charset, email charset add_codec for registering a codec name mapping for use by the charset machinery, and email charset integration with email.message and email.mime and email.policy and email.encoders for building international email senders non-ASCII header encoders Content-Transfer-Encoding selectors charset-aware message constructors and MIME encoding pipelines.

5 min read Feb 11, 2029
AI

Claude Code for email.utils: Python Email Address and Header Utilities

Parse and format RFC 2822 email addresses and dates with Python's email.utils module and Claude Code — email utils parseaddr for splitting a display-name plus angle-bracket address string into a realname and email address tuple, email utils formataddr for combining a realname and address string into a properly quoted RFC 2822 address with angle brackets, email utils getaddresses for parsing a list of raw address header strings each potentially containing multiple comma-separated addresses into a list of realname address tuples, email utils parsedate for parsing an RFC 2822 date string into a nine-tuple compatible with time.mktime, email utils parsedate_tz for parsing an RFC 2822 date string into a ten-tuple that includes the UTC offset timezone in seconds, email utils parsedate_to_datetime for parsing an RFC 2822 date string into an aware datetime object with timezone, email utils formatdate for formatting a POSIX timestamp or the current time as an RFC 2822 date string with optional usegmt and localtime flags, email utils format_datetime for formatting a datetime object as an RFC 2822 date string, email utils make_msgid for generating a globally unique Message-ID string with optional idstring and domain components, email utils decode_rfc2231 for decoding an RFC 2231 encoded parameter value into a tuple of charset language and value, email utils encode_rfc2231 for encoding a string as an RFC 2231 encoded parameter value, email utils collapse_rfc2231_value for collapsing a decoded RFC 2231 tuple to a Unicode string, and email utils integration with email.message and email.headerregistry and datetime and time for building address parsers date formatters message-id generators header extractors and RFC-compliant email construction utilities.

5 min read Feb 10, 2029

Put these ideas into practice

Claude Skills 360 gives you production-ready skills for everything in this article — and 2,350+ more. Start free or go all-in.

Back to Blog

Get 360 skills free