Skip to main content

kaimei

PyPI Python versions License

Official Python client for the Kaimei explainability API.

Kaimei (解明) — to clarify, elucidate, reveal through investigation — turns trained models into something you can inspect: architecture, feature-level attributions, global behaviour, learned rules, robustness, and drift.

from kaimei import Kaimei

client = Kaimei(api_key="km_live_...")

explanation = client.explanations.create(
    model="credit-risk-v3",
    prediction_id="pred_8f2a19",
    input={
        "income": 72000,
        "credit_score": 681,
        "utilization": 0.41,
    },
)

print(explanation.output)
print(explanation.top_features)
# 0.81 decline  |  credit_score -0.22

The same call as POST https://api.kaimei.ai/v1/explanations. See the product site for the language-agnostic REST examples.

Install

pip install kaimei

To extract and upload a fitted estimator you also need NumPy (and your training stack):

pip install "kaimei[models]"

For a local API (the kaimei-api service in the KaimeiAI/kaimei repo):

client = Kaimei(api_key="km_test_...", base_url="http://localhost:8000")

KAIMEI_API_KEY and KAIMEI_BASE_URL are read from the environment when arguments are omitted.

Create an API key in the dashboard (session login). Keys cannot create other keys.

Upload a trained model from a notebook

The client reads the live estimator in your process and uploads layers and learned weights. Small tensors travel inline in the JSON spec; anything larger than 65,536 values is streamed as a zlib-compressed float32 blob and referenced from the spec, so models with millions of parameters upload at about 4 bytes per weight. Kaimei does not store the original .h5 / .pt / pickle file, and it does not host a binary artifact.

from kaimei import Kaimei

client = Kaimei(api_key="km_live_...")

model = client.models.upload(
    clf,  # a fitted estimator
    name="Churn net",
    feature_names=["tenure", "spend", "tickets"],  # optional if the estimator knows them
    X=X_train,   # optional reference rows for explanations (capped at 5,000)
    y=y_train,
)
# Open the dashboard — the architecture scene shows every layer and tensor.

What happens next:

  • Visualize — always. The dashboard draws the uploaded structure.
  • Explain / predict / analyse — when the spec is executable (linear, MLP, decision tree, or a forest of ≤30 trees / ≤4,000 nodes). The API runs that structure in-process.
  • Otherwise — pass a live scoring URL, or POST pre-computed attributions:
client.models.upload(
    large_forest,
    name="Churn forest",
    inference={"type": "remote", "url": "https://scoring.example.com/predict"},
)

Attach weights to a model you already registered with client.models.upload_structure(model.id, clf).

Large models

Nothing changes in the call. A PyTorch module with thousands of layers and millions of parameters uploads the same way; the client registers the model from its shapes, streams each large tensor (progress= reports ("tensors", done, total)), then sends the spec that references them. Module names become block paths, so the dashboard folds encoder.layers.0 … encoder.layers.47 into one ×48 block and loads a tensor only when you open it.

model = client.models.upload(
    transformer,                 # torch.nn.Module, 1,200 layers / 110M parameters
    name="Encoder",
    feature_names=["token_id"],
    progress=lambda stage, done, total: print(stage, done, "/", total),
)

Options:

  • externalize_above= — values per tensor above which it uploads as binary (default 65,536; None keeps everything inline).
  • weights="summary" — upload shapes and statistics only. The architecture is drawable; the weights never leave your environment. Explain / predict then need inference={"type": "remote", ...}.
  • extract_structure(estimator, ...) returns the spec and the tensors without uploading, for inspection or a custom upload.
  • client.models.tensors(model) lists what was uploaded; structure_parameter_values(model, "fc1.weight") reads a tensor back as float32.

A runnable walkthrough lives in examples/upload_sklearn.py and examples/upload_sklearn.ipynb.

Supported estimators

Estimator What is uploaded Executable for explain / predict
sklearn linear (coef_ / intercept_) Exact weights Yes
sklearn MLPClassifier / MLPRegressor Exact layers Yes
sklearn tree Full node list Yes
sklearn forest / extra trees Trees if ≤30 estimators and ≤4,000 nodes; otherwise importances Yes only when trees are inlined
sklearn Pipeline + StandardScaler or (0, 1) MinMaxScaler Scaler folded or inserted, then the estimator Same as the final step
Keras / TensorFlow Dense, Conv2D, pooling, flatten, dropout, LayerNorm Layer weights Yes, unless a layer is unrecognized (approximate)
torch.nn Linear, common activations, Dropout, LayerNorm, Embedding Forward-hook order Yes, unless a layer is unrecognized (approximate)
Wrapper around any of the above (model_, estimator_, best_estimator_, module, …) Same as the inner estimator Same as the inner estimator
XGBoost / LightGBM / CatBoost (sklearn API) feature_importances_ summary No — pass inference remote or attributions
ONNX, Hugging Face, LLMs Framework label only No

Unknown Keras / PyTorch layers are passed through and marked approximate. Those models visualize but cannot be queried unless you add a remote URL.

The JSON spec warns above ~2 MB; lower externalize_above if you see it. Each binary tensor may hold up to 250M values (the API's default cap on a single upload is 512 MB compressed).

What you can do

# Register a model (or point Kaimei at a remote inference URL / built-in demo)
client.models.create(
    name="Credit risk v3",
    slug="credit-risk-v3",
    task="binary_classification",
    features=[
        {"name": "income", "type": "numeric"},
        {"name": "credit_score", "type": "integer"},
        {"name": "utilization", "type": "numeric"},
    ],
    inference={"type": "builtin", "name": "credit-risk"},
)

# Log a prediction your own stack already made
client.predictions.create(model="credit-risk-v3", input={...}, output={"score": 0.81})

# Explain one input. method is "shap" (KernelSHAP), "shapley", or "lime".
client.explanations.create(model="credit-risk-v3", input={...}, method="shap")

# Study the model as a whole, then read the insights
analysis = client.analyses.create(model="credit-risk-v3", type="full")
client.analyses.wait(analysis.id)
insights = client.insights.list(model="credit-risk-v3")

# Walk every page
for model in client.models.iterate():
    print(model.slug)

Dashboard sign-in (session token) is also supported via client.auth.login(...) / client.auth.signup(...). Production sign-up needs a Cloudflare Turnstile token (turnstile_token=...). Prefer creating API keys in the dashboard.

Resources

Attribute Endpoints
client.models /v1/models
client.predictions /v1/predictions
client.explanations /v1/explanations
client.analyses /v1/analyses
client.insights /v1/insights
client.auth /v1/auth
client.api_keys /v1/api-keys
client.organization /v1/organization
client.projects /v1/projects
client.health() /health

Errors raise kaimei.KaimeiError subclasses (AuthenticationError, PermissionDeniedError, NotFoundError, …) and expose .code, .type, and .status_code. PermissionError remains an alias of PermissionDeniedError.

429 responses are retried (honouring Retry-After). GET requests also retry 502/503/504. Default timeout is 120 seconds.

License

Apache 2.0. Copyright Kaimei AI.

Metadata

Release files for kaimei 0.3.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for kaimei 0.3.0
File Size Uploaded Provenance
kaimei-0.3.0.tar.gz 40.4 kB With provenance Details

Built distribution (wheel)

Table of built distributions (wheels) for kaimei 0.3.0
File Interpreter ABI Platform
kaimei-0.3.0-py3-none-any.whl Python 3 none any Details

Total release size: 78.5 kB

Release files / kaimei-0.3.0.tar.gz

Download URL kaimei-0.3.0.tar.gz
Size 40.4 kB
Tags Source
SHA-256 checksum
How to use checksums
15c43f1b2aae9614f2b406e05e8f5f2868a141e6798336cfeda4e25cd5285a9d
BLAKE2b-256 checksum
How to use checksums
0a7bc9c5dfd3a0326debcd124d25aabc803e2e5c7e91be113adb146d0cd4e98d
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 23, 2026.

Transparency log

Release files / kaimei-0.3.0-py3-none-any.whl

Download URL kaimei-0.3.0-py3-none-any.whl
Size 38.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
9101d2b21973ac7bb16ba238e2ebc423e710bcdfc2ed7f271be2c6ad8fba31d2
BLAKE2b-256 checksum
How to use checksums
5ac6f5570cfb59c250e4a6bd24f84ca703207f188fb829475fbc3d92c3c9b088
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 23, 2026.

Transparency log

Security for kaimei 0.3.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

All 2 files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for kaimei-0.3.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 23, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page