Claude Code for Vertex AI: Google Cloud ML Platform — Claude Skills 360 Blog
Blog / AI / Claude Code for Vertex AI: Google Cloud ML Platform
AI

Claude Code for Vertex AI: Google Cloud ML Platform

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

Vertex AI is Google Cloud’s ML platform — unified training, tuning, and serving. pip install google-cloud-aiplatform. aiplatform.init(project="my-project", location="us-central1"). Custom training: job = aiplatform.CustomTrainingJob(display_name="churn-train", script_path="train.py", container_uri="us-docker.pkg.dev/vertex-ai/training/sklearn-cpu.1-2:latest"). model = job.run(replica_count=1, machine_type="n1-standard-4", args=["--epochs=10"]). Pre-built containers for sklearn, XGBoost, TensorFlow, PyTorch, and HuggingFace. model.upload for pre-trained models: aiplatform.Model.upload(display_name="churn-v1", artifact_uri="gs://bucket/model/", serving_container_image_uri="..."). Endpoints: endpoint = aiplatform.Endpoint.create(display_name="churn-endpoint"), model.deploy(endpoint=endpoint, machine_type="n1-standard-2", min_replica_count=1, max_replica_count=5). endpoint.predict(instances=[[1.0, 2.0, 3.0]]). Batch Prediction: model.batch_predict(job_display_name="batch-score", gcs_source="gs://bucket/input/*.jsonl", gcs_destination_prefix="gs://bucket/output/", machine_type="n1-standard-4"). Vertex Pipelines: @component and @pipeline decorators from kfp.dsl, compiler.Compiler().compile(pipeline_func, "pipeline.yaml"), aiplatform.PipelineJob(template_path="pipeline.yaml").submit(). Feature Store: FeatureStore.create(...), EntityType.create(...), Feature.create(...), entity_type.ingest_from_df(df, feature_time="timestamp_col"), entity_type.read(entity_ids=["user_1"]). Model Garden: aiplatform.PublisherModel(model_name="publishers/google/models/gemini-1.5-flash-001"). Claude Code generates Vertex AI training jobs, pipeline components, endpoint deployments, feature store setups, and TypeScript prediction clients.

CLAUDE.md for Vertex AI

## Vertex AI Stack
- SDK: google-cloud-aiplatform >= 1.50
- Init: aiplatform.init(project=GCP_PROJECT, location="us-central1")
- Training: CustomTrainingJob(script_path, container_uri).run(machine_type, args)
- Upload: aiplatform.Model.upload(artifact_uri="gs://", serving_container_image_uri)
- Endpoint: model.deploy(endpoint, machine_type, min_replica_count, max_replica_count)
- Batch: model.batch_predict(gcs_source, gcs_destination_prefix, machine_type)
- Pipelines: @kfp.dsl.component + @kfp.dsl.pipeline → PipelineJob.submit()
- Features: FeatureStore → EntityType → Feature → ingest_from_df / read

Training Script (GCS artifacts)

# train.py — Vertex AI custom training entry point
from __future__ import annotations
import argparse
import json
import os
import pickle
from pathlib import Path

import numpy as np
import pandas as pd
from sklearn.ensemble import GradientBoostingClassifier
from sklearn.metrics import roc_auc_score
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from google.cloud import storage


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser()
    parser.add_argument("--n-estimators",    type=int,   default=200)
    parser.add_argument("--learning-rate",   type=float, default=0.05)
    parser.add_argument("--max-depth",       type=int,   default=4)
    parser.add_argument("--train-data",      type=str,   required=True)  # gs:// path
    parser.add_argument("--test-data",       type=str,   default="")
    # AIP_MODEL_DIR set by Vertex AI for artifact output
    parser.add_argument("--model-dir",       type=str,   default=os.environ.get("AIP_MODEL_DIR", "/tmp/model"))
    return parser.parse_args()


def read_gcs_csv(gcs_path: str) -> pd.DataFrame:
    """Read CSV from GCS, returning a DataFrame."""
    return pd.read_csv(gcs_path)


def upload_to_gcs(local_path: str, gcs_uri: str) -> None:
    """Upload a local file to GCS."""
    gcs_uri     = gcs_uri.replace("gs://", "")
    bucket_name, *blob_parts = gcs_uri.split("/")
    blob_name   = "/".join(blob_parts)
    storage.Client().bucket(bucket_name).blob(blob_name).upload_from_filename(local_path)


def main():
    args    = parse_args()
    feature_cols = ["age", "tenure_days", "monthly_spend", "support_tickets", "last_login_days"]
    target_col   = "churned"

    train_df = read_gcs_csv(args.train_data)
    test_df  = read_gcs_csv(args.test_data) if args.test_data else train_df.sample(frac=0.2)

    X_train, y_train = train_df[feature_cols].values, train_df[target_col].values
    X_test,  y_test  = test_df[feature_cols].values,  test_df[target_col].values

    pipeline = Pipeline([
        ("scaler",  StandardScaler()),
        ("clf",     GradientBoostingClassifier(
            n_estimators=args.n_estimators,
            learning_rate=args.learning_rate,
            max_depth=args.max_depth,
            random_state=42,
        )),
    ])
    pipeline.fit(X_train, y_train)

    auc = roc_auc_score(y_test, pipeline.predict_proba(X_test)[:, 1])
    print(f"AUC-ROC: {auc:.4f}")

    # Vertex AI expects model artifacts in AIP_MODEL_DIR
    os.makedirs(args.model_dir, exist_ok=True)
    model_path = os.path.join(args.model_dir, "model.pkl")
    with open(model_path, "wb") as f:
        pickle.dump(pipeline, f)

    # Write metadata for Model Evaluation
    metadata = {"auc": auc, "framework": "sklearn", "features": feature_cols}
    with open(os.path.join(args.model_dir, "metadata.json"), "w") as f:
        json.dump(metadata, f)

    print(f"Model saved to {args.model_dir}")


if __name__ == "__main__":
    main()

Vertex AI SDK Workflow

# ml/vertex_workflow.py — training, deployment, and batch prediction
from __future__ import annotations
from google.cloud import aiplatform
from kfp import dsl, compiler
from kfp.dsl import component, Output, Model, Metrics

PROJECT    = "my-gcp-project"
LOCATION   = "us-central1"
BUCKET     = "gs://my-ml-bucket"
REPO       = f"us-central1-docker.pkg.dev/{PROJECT}/ml-images"


def init_vertex():
    aiplatform.init(project=PROJECT, location=LOCATION, staging_bucket=BUCKET)


# ── Training ────────────────────────────────────────────────────────────────

def run_training_job(
    train_data: str = f"{BUCKET}/data/train.csv",
    test_data:  str = f"{BUCKET}/data/test.csv",
) -> aiplatform.Model:
    init_vertex()

    job = aiplatform.CustomTrainingJob(
        display_name="churn-model-training",
        script_path="train.py",
        container_uri="us-docker.pkg.dev/vertex-ai/training/sklearn-cpu.1-2:latest",
        requirements=["google-cloud-storage>=2.0"],
        model_serving_container_image_uri="us-docker.pkg.dev/vertex-ai/prediction/sklearn-cpu.1-2:latest",
    )

    model = job.run(
        model_display_name="churn-classifier",
        replica_count=1,
        machine_type="n1-standard-4",
        args=[
            f"--train-data={train_data}",
            f"--test-data={test_data}",
            "--n-estimators=200",
            "--learning-rate=0.05",
        ],
        base_output_dir=f"{BUCKET}/training-output",
        sync=True,
    )
    print(f"Model trained: {model.resource_name}")
    return model


# ── Endpoint deployment ──────────────────────────────────────────────────────

def deploy_endpoint(
    model:          aiplatform.Model,
    endpoint_name:  str = "churn-prod",
    machine_type:   str = "n1-standard-2",
) -> aiplatform.Endpoint:
    init_vertex()

    endpoint = aiplatform.Endpoint.create(
        display_name=endpoint_name,
        labels={"env": "production", "team": "ml"},
    )

    model.deploy(
        endpoint=endpoint,
        deployed_model_display_name=f"{endpoint_name}-v1",
        machine_type=machine_type,
        min_replica_count=1,
        max_replica_count=5,
        traffic_split={"0": 100},
        accelerator_type=None,
        explanation_metadata=None,
        explanation_parameters=None,
    )

    print(f"Deployed to endpoint: {endpoint.resource_name}")
    return endpoint


# ── Batch prediction ─────────────────────────────────────────────────────────

def run_batch_prediction(
    model:    aiplatform.Model,
    gcs_src:  str = f"{BUCKET}/batch-input/*.jsonl",
    gcs_dest: str = f"{BUCKET}/batch-output/",
) -> aiplatform.BatchPredictionJob:
    init_vertex()

    job = model.batch_predict(
        job_display_name="churn-batch-score",
        gcs_source=gcs_src,
        gcs_destination_prefix=gcs_dest,
        instances_format="jsonl",
        predictions_format="jsonl",
        machine_type="n1-standard-4",
        starting_replica_count=2,
        max_replica_count=10,
        sync=True,
    )
    print(f"Batch job complete: {job.resource_name}")
    return job


# ── Vertex Pipelines ─────────────────────────────────────────────────────────

@component(
    base_image="us-docker.pkg.dev/vertex-ai/training/sklearn-cpu.1-2:latest",
    packages_to_install=["google-cloud-aiplatform>=1.50"],
)
def train_component(
    project:       str,
    location:      str,
    train_data:    str,
    auc_threshold: float,
    model:         Output[Model],
    metrics:       Output[Metrics],
):
    """Kubeflow pipeline component that trains and writes a model artifact."""
    from google.cloud import aiplatform as aip
    import pickle, json, os
    from sklearn.ensemble import GradientBoostingClassifier
    from sklearn.pipeline import Pipeline
    from sklearn.preprocessing import StandardScaler
    from sklearn.metrics import roc_auc_score
    import pandas as pd

    aip.init(project=project, location=location)
    df = pd.read_csv(train_data)
    feature_cols = ["age", "tenure_days", "monthly_spend", "support_tickets", "last_login_days"]
    pipe = Pipeline([("sc", StandardScaler()), ("clf", GradientBoostingClassifier())])
    pipe.fit(df[feature_cols], df["churned"])
    auc = roc_auc_score(df["churned"], pipe.predict_proba(df[feature_cols])[:, 1])

    os.makedirs(model.path, exist_ok=True)
    with open(os.path.join(model.path, "model.pkl"), "wb") as f:
        pickle.dump(pipe, f)
    metrics.log_metric("auc", auc)
    print(f"Component AUC: {auc:.4f}")


@dsl.pipeline(name="churn-training-pipeline", description="Train and register churn model")
def churn_pipeline(
    project:       str = PROJECT,
    location:      str = LOCATION,
    train_data:    str = f"{BUCKET}/data/train.csv",
    auc_threshold: float = 0.75,
):
    train_task = train_component(
        project=project,
        location=location,
        train_data=train_data,
        auc_threshold=auc_threshold,
    )
    train_task.set_cpu_limit("4").set_memory_limit("16G")


def compile_and_run_pipeline() -> None:
    init_vertex()
    compiler.Compiler().compile(churn_pipeline, "churn_pipeline.yaml")

    pipeline_job = aiplatform.PipelineJob(
        display_name="churn-pipeline-run",
        template_path="churn_pipeline.yaml",
        parameter_values={
            "project":    PROJECT,
            "location":   LOCATION,
            "train_data": f"{BUCKET}/data/train.csv",
        },
    )
    pipeline_job.submit(service_account=f"vertex-sa@{PROJECT}.iam.gserviceaccount.com")
    print(f"Pipeline submitted: {pipeline_job.resource_name}")

TypeScript Client

// lib/vertex/client.ts — TypeScript client for Vertex AI endpoints
import { PredictionServiceClient } from "@google-cloud/aiplatform"
import { helpers } from "@google-cloud/aiplatform"

const PROJECT  = process.env.GCP_PROJECT  ?? "my-gcp-project"
const LOCATION = process.env.GCP_LOCATION ?? "us-central1"

const predictionClient = new PredictionServiceClient({
  apiEndpoint: `${LOCATION}-aiplatform.googleapis.com`,
})

export type ChurnInput = {
  age:             number
  tenure_days:     number
  monthly_spend:   number
  support_tickets: number
  last_login_days: number
}

export type ChurnPrediction = {
  churn_probability: number
  risk_tier:         "HIGH" | "MEDIUM" | "LOW"
}

export async function predictChurn(
  endpointId: string,
  records:    ChurnInput[],
): Promise<ChurnPrediction[]> {
  const endpoint = `projects/${PROJECT}/locations/${LOCATION}/endpoints/${endpointId}`

  const instances = records.map(r =>
    helpers.toValue({
      instances: [[r.age, r.tenure_days, r.monthly_spend, r.support_tickets, r.last_login_days]],
    })
  )

  const [response] = await predictionClient.predict({
    endpoint,
    instances,
  })

  return (response.predictions ?? []).map((pred: any) => {
    const probs = helpers.fromValue(pred) as number[]
    const prob  = Array.isArray(probs) ? probs[1] ?? probs[0] : 0
    return {
      churn_probability: Math.round(prob * 10000) / 10000,
      risk_tier: prob > 0.7 ? "HIGH" : prob > 0.3 ? "MEDIUM" : "LOW",
    }
  })
}

For the SageMaker alternative when your infrastructure is AWS-native with data in S3, existing IAM roles, and VPC configurations — SageMaker integrates with Glue, Athena, and Redshift while Vertex AI is the natural choice for GCP-native teams with BigQuery data warehouses and existing Cloud Storage and IAM configurations. For the Kubeflow (self-managed) alternative when needing full control over the Kubeflow infrastructure running inside your own Kubernetes cluster without Google Cloud dependency — self-managed Kubeflow gives complete portability while Vertex AI Pipelines manages the orchestration layer as a fully-managed service, eliminating cluster maintenance overhead. The Claude Skills 360 bundle includes Vertex AI skill sets covering custom training jobs, endpoint deployment, batch prediction, Kubeflow pipeline components, and TypeScript prediction clients. Start with the free tier to try GCP ML workflow 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