# Explain

> Explain scikit-learn and XGBoost model predictions with per-row SHAP values and global feature importance

This page includes setup, release pins, credentials, hosting and verification evidence. [JSON alternative](https://query.farm/products/orchard/api/v1/connectors/explain.json) contains the same setup facts for structured readers; choose one format.

## Runtime and release

Use DuckDB or Haybarn **2.0.1** with **VGI protocol 3.4**.
Catalog alias: `explain`. Release: [v0.5.0](https://github.com/Query-farm/vgi-explain/releases/tag/v0.5.0). Metadata generated: 2026-12-01T18:22:16+00:00.

## Choose where it runs

- On your machine: use an installation method below. No Query Farm account is required for local execution.
- Self-host: follow [the connector deployment instructions](https://github.com/Query-farm/vgi-explain) and [connection guide](https://query.farm/vgi/connect-to-a-worker/). Use your real endpoint and its authentication settings.
- Query Farm hosted: [create a deployment](https://auth.queryfarm.cloud/console/new?worker=explain). Hosting has a $10 monthly minimum per organization; usage and license fees may apply. Copy the deployment-specific ATTACH from the console.

## Service credentials and prerequisites

No service credentials are declared by this connector. Individual datasets, input files or deployments may have their own prerequisites.

Secret parameter required flags describe the upstream declaration; they do not override the service-level mode above. Keep secrets in environment variables or the deployment secret store. SQL values in angle brackets are placeholders, not automatic environment lookups. Native DuckDB and Haybarn 2.0.1 do not provide a SQL getenv() function, even when worker-supplied snippets mention it. Read environment variables in your application and pass credential values through client parameter bindings (for example, Python con.execute("CREATE SECRET stripe (TYPE stripe, api_key ?)", [os.environ["STRIPE_API_KEY"]]) after attaching the connector. Omit unused optional parameters and keep real values out of saved SQL and logs.

## Install the extension

In stock DuckDB:

```sql
SET allow_extension_repositories = 'allowed';

CREATE EXTENSION REPOSITORY IF NOT EXISTS query_farm
    WITH PREFIX 'https://duckdb-extensions.query.farm';

INSTALL vgi FROM query_farm;
LOAD vgi FROM query_farm;
```

In Haybarn:

```sql
INSTALL vgi FROM community;
LOAD vgi;
```

## Attach the connector

The local recipes below pin the catalog release for repeatability. A public demo endpoint follows its deployed release.

### uvx

Attach with uvx

Needs uv. uvx builds the worker from its release tag on first attach and reuses the cached environment after that.

```sql
ATTACH 'explain' AS explain (
  TYPE vgi,
  LOCATION 'uvx --from git+https://github.com/Query-farm/vgi-explain@v0.5.0 vgi-explain'
);
```

### Docker

Attach the signed image

Needs Docker, Podman or another OCI runtime. The extension runs the container and talks to it over stdio.

```sql
ATTACH 'explain' AS explain (
  TYPE vgi,
  LOCATION 'oci://ghcr.io/query-farm/vgi-explain:0.5.0'
);
```

## See which features drive a model’s predictions

Service credentials required for this example: not declared by this example; check the connector requirements above.

```sql
SET VARIABLE m = (SELECT model FROM read_parquet('https://raw.githubusercontent.com/Query-farm/vgi-explain/v0.2.0/test/fixtures/models.parquet') WHERE name = 'rf_clf'); SELECT feature, rank, method FROM explain.main.feature_importance((SELECT id, signal, noise_a, noise_b FROM read_parquet('https://raw.githubusercontent.com/Query-farm/vgi-explain/v0.2.0/test/fixtures/features.parquet')), model := getvariable('m'), id := 'id') ORDER BY rank
```

- [explain.main.feature_importance — table_in_out_function](https://query.farm/products/orchard/connectors/explain/objects/table_in_out_function.bWFpbg.ZmVhdHVyZV9pbXBvcnRhbmNl.md): exact declaration for this example.

Execution evidence: **captured_result**.

```json
{
  "status": "captured_result",
  "capturedAt": "2026-12-01T06:16:30+00:00",
  "engineVersion": "2.0.1",
  "protocolVersion": "3.4.0",
  "releaseTag": "v0.5.0",
  "sample": {
    "columns": [
      "feature",
      "rank",
      "method"
    ],
    "types": [
      "VARCHAR",
      "INTEGER",
      "VARCHAR"
    ],
    "rows": [
      [
        "signal",
        1,
        "mean_abs_shap"
      ],
      [
        "noise_b",
        2,
        "mean_abs_shap"
      ],
      [
        "noise_a",
        3,
        "mean_abs_shap"
      ]
    ],
    "more": false
  }
}
```

## Connector reference

### SHAP Model Explanations in SQL

![SHAP logo](https://raw.githubusercontent.com/shap/shap/master/docs/artwork/shap_logo.png)

**Explainable AI for machine learning predictions, right inside DuckDB — compute SHAP (SHapley Additive exPlanations) feature attributions for fitted scikit-learn and XGBoost models with plain SQL.**

The `explain` catalog turns model interpretability into a set of DuckDB/SQL table functions, so you can answer *why* a model made a prediction without leaving your database or writing any Python. It is built for data engineers, analysts, and ML practitioners who need transparent, auditable, per-prediction explanations — for model debugging, regulatory and fair-lending reviews, feature selection, or simply building trust in a model's output. Every explanation is computed over your data in place via Apache Arrow, so it composes naturally with joins, filters, and aggregates in ordinary SQL.

Under the hood the worker is powered by [SHAP](https://github.com/shap/shap), the reference implementation of Shapley-value feature attribution ([documentation](https://shap.readthedocs.io/en/latest/)), grounded in cooperative game theory's [Shapley values](https://en.wikipedia.org/wiki/Shapley_value). Importantly, vgi-explain does **not** train models — it *interprets* the self-contained *model* `BLOB` produced by the sibling `vgi-sklearn` ([scikit-learn](https://scikit-learn.org/)) and `vgi-xgboost` ([XGBoost](https://xgboost.readthedocs.io/)) workers. SHAP automatically selects an appropriate explainer (e.g. TreeExplainer for tree ensembles), so explanations are exact and fast for the supported model families. Because a DuckDB table function accepts only one subquery argument (reserved for the feature relation), the model travels as a scalar `model` argument, usually held in a session variable and read with `getvariable('m')` — see the schema's and each function's example queries for ready-to-run SQL.

Three functions make up the surface. `shap_values` streams a feature relation and emits per-row, per-feature signed contributions in long format (with a contribution per class for multi-class classifiers), aligning input columns to the model's fitted features by name. `shap_base_value` returns the explainer's expected value — the model's baseline output that the per-feature contributions add onto, so that base value + sum(contributions) reproduces the prediction (SHAP's additivity property). `feature_importance` aggregates `mean(|SHAP|)` across a relation to produce a global, ranked importance of which features matter most, falling back to the model's native importances when no rows are supplied. Together they cover local (single-prediction) and global (whole-dataset) interpretability for the models you already serve from VGI.

## Find the exact SQL object

[Browse 4 object declarations](https://query.farm/products/orchard/api/v1/connectors/explain/objects.json) or [search within this connector](https://query.farm/products/orchard/api/v1/search.json?kind=object&connector=explain&q=explain).

Follow one format of each needed object for complete argument types, defaults, named flags, return columns and examples. Existing links above can replace another search. For questions about hosting, credentials or supported operations, stop once the documentation answers the question; SQL and unrelated object lookups are unnecessary.

## Verification and interpretation

- Missing, null, or undeclared metadata means unknown; do not invent defaults, credential scope, platform support or endpoint URLs.
- Search is keyword retrieval, not proof of a capability. Read the exact object declaration before generating SQL.
- A table and a table function can have the same name. Preserve parentheses and use the matching overload and schema.
- Service credentials, external data availability and deployment authentication are separate requirements.
- Catalog verification records the harvest environment. It is not proof that every query or current live API call succeeds. Only an example with captured_result has a saved result for that exact SQL.

```json
{
  "generatedAt": "2026-12-01T18:22:16+00:00",
  "repository": "https://github.com/Query-farm/vgi-explain",
  "harvest": {
    "status": "ok",
    "method": "subprocess",
    "error": null,
    "vgi_version": "9773130dde"
  },
  "catalogVerification": {
    "verified": true,
    "status": "passed",
    "total": 4,
    "passed": 4,
    "failed": 0,
    "needs_credentials": 0,
    "location": "uvx --from git+https://github.com/Query-farm/vgi-explain@v0.5.0 vgi-explain",
    "transport": "subprocess",
    "environment": {
      "vgi_extension_version": "9773130dde",
      "haybarn_version": "2.0.1rc3",
      "engine_version": "v2.0.1",
      "python": "3.12.4",
      "platform": "darwin_arm64",
      "protocol_version": "3.4.0"
    },
    "checked_at": "2026-12-01T06:14:04+00:00"
  },
  "interpretation": "Catalog verification records the harvest environment. It is not proof that every query or current live API call succeeds. Only an example with captured_result has a saved result for that exact SQL."
}
```
