> ## Documentation Index
> Fetch the complete documentation index at: https://docs.chowder.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Python API

> Configure engines, run SQL, and read results from Python.

Use the Python API to configure Chowder, submit SQL, and consume results.

## Module functions

| Export | Purpose |
| - | - |
| `chowder.sql(query)` | Plan SQL on the lazy process-wide default engine. |
| `chowder.default_engine()` | Return the process-wide default `Engine`. |
| `chowder.interrupt()` | Interrupt active work on the default engine without creating one. |
| `chowder.close()` | Close the default engine. |
| `chowder.clear_cache(*, artifacts=False)` | Clear durable results for the default engine and return a `CacheClearSnapshot`. |
| [`chowder.display(obj, ...)`](#inspect-query-results-in-a-notebook) | Display a materialized Arrow, Polars, or pandas table in a notebook. |
| `chowder.serve(...)` | Run an Arrow Flight server until interrupted. |

For general queries, use the module-level API and materialize before displaying:

```python theme={"theme":"css-variables","languages":{"custom":["/languages/chowder-sql.json"]}}
import chowder

SQL = """
SELECT
    title,
    content
FROM read_parquet('hf://buckets/chowderai/chowder-demo/parquet/data/amazon-reviews/*.parquet')
LIMIT 3;
"""

relation = chowder.sql(SQL)
result = relation.to_polars()

chowder.display(result)
```

## `Engine`

```python theme={"theme":"css-variables","languages":{"custom":["/languages/chowder-sql.json"]}}
chowder.Engine(
    *,
    cache_dir=None,
    location=None,
    remote=None,
    num_gpus=None,
    token=None,
    embed_config=None,
    local_runtime=None,
    reader_config=None,
    progress=None,
)
```

| Parameter | Type | Description |
| - | - | - |
| `cache_dir` | `str \| None` | Durable result-cache root. |
| `location` | `str \| None` | Explicit remote endpoint; overrides `CHOWDER_API_URL`. Cannot be combined with `remote=False`. |
| `remote` | `bool \| None` | `True` opts in to remote compute; `False` forces local compute. `None` follows `CHOWDER_REMOTE` (off by default). |
| `num_gpus` | `int \| None` | Remote-only GPU request from 1 through 64 for each GPU stage. `SET chowder.num_gpus` overrides it for a session; see [Configuration](https://docs.chowder.ai/reference/configuration.md#sql-session-settings). |
| `token` | `str \| None` | Client credential; falls back to `CHOWDER_API_TOKEN` when omitted or blank. Unused by local engines. |
| `embed_config` | `EmbedConfig \| None` | Embedding options, such as `normalize`. |
| `local_runtime` | `LocalRuntimeConfig \| Mapping \| None` | Typed local model, ONNX, and transcription configuration. |
| `reader_config` | `ReaderConfig \| Mapping \| None` | How many sources Chowder reads at once. |
| `progress` | `bool \| ProgressMode \| None` | `auto`, `tty`, `plain`, `json`, or `off`; Booleans also work. |

A remote engine without an explicit `location` requires `CHOWDER_API_URL`. If the URL is unset or blank, creating the engine raises `ValueError`. Setting that URL and `CHOWDER_API_TOKEN` alone does not opt in. The default engine used by `chowder.sql()` follows `CHOWDER_REMOTE` when first created.

See [Connect to remote AI compute](https://docs.chowder.ai/guides/remote-compute.md) for remote selection and authentication.

### Automatic cleanup

You can also use an engine as a context manager. The `with` block closes it automatically when the block exits, including when an exception occurs. Materialize the result before leaving the block:

```python theme={"theme":"css-variables","languages":{"custom":["/languages/chowder-sql.json"]}}
import chowder

SQL = """
SELECT 1 AS ready
"""

with chowder.Engine(remote=False) as engine:
    relation = engine.sql(SQL)
    result = relation.to_polars()

chowder.display(result)
```

The materialized result remains usable after the engine closes. Engine construction itself does not load a model.

General query construction is not thread-safe. Give each submitting thread its own engine. `engine.interrupt()` is thread-safe so another thread can stop active work.

### Query and lifecycle methods

| Method | Description |
| - | - |
| `engine.sql(query)` | Return a `Relation` for read-only SQL or a `StatementResult` for side-effecting SQL. |
| `engine.status()` | Return requested configuration, backend state, cache state, and local or remote capabilities. |
| `engine.interrupt()` | Interrupt active work on this engine. |
| `engine.clear_cache(artifacts=False)` | Clear durable results; preserve model and runtime artifacts by default. |
| `engine.close()` | Close the session, model processes, readers, and remote client. |

Pass `artifacts=True` only when you also want to remove Chowder-owned model weights, runtime bundles, and compiled artifacts. It does not remove the third-party Hugging Face cache.

### Source methods

Each method mirrors `SELECT * FROM <function>(...)` and returns a `Relation`:

```python theme={"theme":"css-variables","languages":{"custom":["/languages/chowder-sql.json"]}}
engine.read_documents(pattern)
engine.read_images(pattern)
engine.read_videos(pattern, window_s=5.0)
engine.read_audio(pattern, window_s=5.0)
engine.read_text(pattern)
engine.read_json(pattern)
engine.read_csv(pattern)
engine.read_parquet(pattern)
engine.read_mcap(pattern)
```

### In-scope tables

An unresolved SQL table name can bind to a same-named object in the caller's scope. Supported inputs include PyArrow tables and datasets, Arrow record-batch readers and C streams, Polars DataFrames, pandas DataFrames, and a same-engine `Relation`.

```python theme={"theme":"css-variables","languages":{"custom":["/languages/chowder-sql.json"]}}
import chowder

SQL = """
SELECT
    title,
    content
FROM read_parquet('hf://buckets/chowderai/chowder-demo/parquet/data/amazon-reviews/*.parquet')
"""

relation = chowder.sql(SQL)
reviews = relation.to_polars()

SQL = """
SELECT
    title,
    content
FROM reviews
WHERE content ILIKE '%battery%'
LIMIT 5
"""

relation = chowder.sql(SQL)
result = relation.to_polars()

chowder.display(result)
```

The relation keeps a reference to `reviews` until you close or consume it.

## Result types

`SqlResult` is the type alias `Relation | StatementResult`.

### `Relation`

A `Relation` is a lazy, executable query plan for read-only SQL. Iterate over it to stream Arrow batches, or materialize the results as an Arrow table or DataFrame. Displaying or inspecting it does not read a source or load a model.

| Member | Description |
| - | - |
| `relation.schema` | Exact Arrow schema known at planning time. |
| `relation.sql` | Original SQL text. |
| `relation.explain()` | Optimized physical plan without data execution. |
| `for batch in relation` | Execute and stream `pyarrow.RecordBatch` objects. |
| `relation.to_arrow_table()` | Execute and materialize a `pyarrow.Table`. |
| `relation.to_polars()` | Execute and materialize a Polars DataFrame. |
| `relation.to_pandas()` | Execute and materialize a pandas DataFrame. |
| `relation.close()` | Release its pending reader and captured registrations. |
| `with relation:` | Close the relation automatically when the block exits. |

Every consumption starts an independent execution of the same bound plan. A relation over a single-use captured reader is the documented exception and cannot be replayed.

`Relation` implements the Arrow C stream protocol:

```python theme={"theme":"css-variables","languages":{"custom":["/languages/chowder-sql.json"]}}
import polars as pl

frame = pl.from_arrow(relation)
```

Use a Chowder materializer when you need Chowder's typed exception taxonomy. Arrow C stream consumers carry error text but raise their own Arrow exception type.

### `StatementResult`

A `StatementResult` represents side-effecting SQL. Its output can be consumed once. It cannot be replayed or explained because rebuilding its plan could repeat the side effect. Like `Relation`, it supports `close()` and `with` blocks.

## Inspect query results in a notebook

Use `chowder.display()` to inspect nested structs, arrays, and supported image columns. Pass a Polars or pandas DataFrame, a PyArrow table, or a PyArrow record batch. If you have a `Relation`, materialize it first with a method such as `to_polars()`.

The keyword arguments below show the defaults for how many rows and columns to display, how large image previews can be, and the maximum encoded size of a source image.

```python theme={"theme":"css-variables","languages":{"custom":["/languages/chowder-sql.json"]}}
chowder.display(
    result,
    max_rows=20,
    max_columns=20,
    image_width=256,
    image_height=192,
    max_image_bytes=32 * 1024 * 1024,
)
```

## Additional APIs

Open these sections when you need configuration types, serving, or error handling.

> [accordion] Typed configuration
>
> | Type | Fields |
> | - | - |
> | `EmbedConfig` | `normalize=True` |
> | `ReaderConfig` | `source_concurrency=4` |
> | `LlamaCppConfig` | `parallel`, `ctx_size`, `batch_size`, `ubatch_size`, `threads`, `threads_batch`, `gpu_layers`, `flash_attn`, `cont_batching`, `context_shift`, `kv_unified`, `mlock`, `cache_ram`, `image_max_tokens` |
> | `OnnxRuntimeConfig` | `providers`, `provider_options`, `intra_op_num_threads`, `inter_op_num_threads`, `execution_mode`, `graph_optimization_level` |
> | `WhisperCppConfig` | `use_gpu`, `flash_attn`, `gpu_device`, `threads` |
> | `LocalTranscriptionConfig` | `model`, `whisper_cpp` |
> | `LocalRuntimeConfig` | `llama_cpp`, `onnx_runtime`, `transcription` |
>
> Chowder selects the model for each AI operation; see [Models](https://docs.chowder.ai/concepts/models.md).

> [accordion] Serve remote compute
>
> ```python theme={"theme":"css-variables","languages":{"custom":["/languages/chowder-sql.json"]}}
> chowder.serve(
>     location=None,
>     *,
>     protocol=None,
>     local_runtime=None,
>     reader_config=None,
> )
> ```
>
> `serve` runs a Chowder Arrow Flight server and blocks the calling thread. `location=None` binds `grpc://127.0.0.1:8816`, and `protocol=None` uses `"flight"`. `local_runtime` configures server-owned document parsing and transcription runtimes. Remote AI functions use the server’s configured inference routes. `reader_config` bounds independently admitted sources. Use the same Chowder version on the client and server. See [Self-host AI compute](https://docs.chowder.ai/guides/self-host-ai-compute.md) for deployment setup.

> [accordion] Errors
>
> | Error | Meaning |
> | - | - |
> | `SQLError` | Base SQL runtime error with `status` and `code`. |
> | `SQLPlanningError` | Parsing, binding, or physical planning failed. |
> | `SQLExecutionError` | Work failed after execution began. |
> | `QueryCancelledError` | A query was cancelled. Derives from `InterruptedError`, not `SQLError`. |
> | `ModelMemoryError` | A local model could not fit available memory. |
>
> Closing the parent engine invalidates outstanding results. Consume or close them before leaving the engine context.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.