Files
lancedb/docs/web/curation/create-function.mdx
Brendan Clement 27b7a248e4 docs: use refresh_column_async with wait on Enterprise pages (#5183)
## The problem

Several Python examples on Enterprise pages start a computed column
refresh with `table.refresh_column(...)`. On a LanceDB Enterprise
connection that call always fails:

```
NotImplementedError: not supported: a remote refresh runs as a server job; use refresh_column_async and wait on the returned handle
```

On Enterprise a refresh runs as a job on the server. Only
`refresh_column_async(...)` works there: it returns a job, and
`job.wait()` blocks until the job finishes. A reader following the
quickstart's Enterprise step, or the secrets or GPU examples, hits the
error. The same fix landed for the Sophon-owned page in
lancedb/sophon#10478.

## What this changes

- **The examples use the job form:** `job =
table.refresh_column_async(...)` then `job.wait()`. This covers
`curation/vend-secret.mdx`, `curation/create-function.mdx` and the
quickstart, plus the sentences that named the blocking call in
`enterprise/auto-refresh.mdx` and
`feature-engineering/add-computed-column.mdx`.
- **The quickstart example now comes from a test.** The
`PyQuickstartAddFeature` snippet is generated from the deployment test
in `docs/web-tests/py/test_quickstart.py`, and the separate
Enterprise-only snippet is folded into it. That test also asserts that
the blocking call raises an error naming `refresh_column_async`.
- **The GPU example only shows arguments the Enterprise table accepts
today.** `gpu_class` and `gpu_count` are dropped from `add_columns`, and
`gpu_count` from the refresh call, with a one-sentence note. See "Python
wrapper gap" below.

## How it was checked

Every Enterprise call the changed pages show was run through the Python
SDK (0.42.0b26, built from this branch) against a local stand-in for an
Enterprise server that returns canned responses:

- `table.refresh_column("embedding")` raises the error above and sends
no request.
- `job = table.refresh_column_async("embedding"); job.wait()` submits a
refresh job and returns its result.
- `table.refresh_column_async("embedding", gpu_class="h100",
total_gpu_count=8).wait()` is accepted, and the server receives both GPU
options.
- The removed forms fail as expected: `gpu_count` on
`refresh_column_async`, and `gpu_class` or `gpu_count` on `add_columns`,
raise `TypeError: unexpected keyword argument`.

Also: the committed quickstart snippet matches what the generator
produces from the test, and the five changed pages render with no
blocking call in a local preview.

**Not run:** the quickstart deployment test itself. It needs a real
Enterprise deployment and is skipped without credentials, which CI does
not have. Registering a Function also needs a real deployment, so that
line of the GPU example was not exercised.

## Python wrapper gap (to be fixed separately)

The Python `RemoteTable.refresh_column_async` and
`RemoteTable.add_columns` do not accept `gpu_count`, and `add_columns`
also does not accept `gpu_class`. The Rust remote table supports these
GPU placement options, so this looks like an oversight in the Python
layer. This PR makes no SDK change. Once the wrapper passes them
through, the GPU example can show them again.

## Risk

Low. Docs and docs tests only.

## Pipeline

Updates from [git push
no-mistakes](https://github.com/kunchenguid/no-mistakes)

<!-- no-mistakes-pipeline-attestation:v1
{"head_sha":"11ac1a260e8825dd406dea4e839f2498309e843b","steps":[{"step":"intent","status":"completed"},{"step":"rebase","status":"completed"},{"step":"review","status":"completed"},{"step":"test","status":"completed"},{"step":"document","status":"completed"},{"step":"lint","status":"completed"},{"step":"push","status":"completed"},{"step":"pr","status":"running"},{"step":"ci","status":"pending"}],"live_validation":{"verdict":"go","live":7,"total":9}}
-->

<details>
<summary>✅ **Intent** - passed</summary>

✅ No issues found.
</details>

<details>
<summary>✅ **Rebase** - passed</summary>

✅ No issues found.
</details>

<details>
<summary>✅ **Review** - passed</summary>

✅ No issues found.
</details>

<details>
<summary>⚠️ **Test** - 2 infos</summary>

- ⚠️ `docs/web/curation/create-function.mdx:546` - Not confirmed live.
The new example calls `table.refresh_column_async(&#34;embedding&#34;,
gpu_class=&#34;h100&#34;, gpu_count=4, total_gpu_count=8)`, but
`RemoteTable.refresh_column_async` in
python/python/lancedb/remote/table.py (line 1280) has no `gpu_count`
parameter (only `gpu_class` and `total_gpu_count`), while the abstract
`Table` and `LanceTable` do. If that reading holds, the documented call
raises `TypeError: unexpected keyword argument &#39;gpu_count&#39;` on
Enterprise. The blocking `RemoteTable.refresh_column` has the same gap,
so this predates the change, but the page still shows a call that may
not run. Decision needed: drop `gpu_count=4` from the example, or add
the parameter to the Enterprise table (an SDK change beyond this docs
change).
- ⚠️ The intent asked whether the docs change can be validated by
running code. In this run it could not: the SDK build did not finish in
the time budget and no Enterprise deployment credentials are available,
so the only test covering the changed quickstart snippet
(`test_quickstart_derived_feature_on_a_deployment`) skips. The prepared
driver script in the evidence directory exercises the three documented
calls against a localhost emulator once the SDK is built.
- ⚠️ live validation verdict: inconclusive (4 of 7 scenarios were driven
live against the product); untested: On an Enterprise connection
(localhost emulator, synthetic responses) the documented `job =
table.refresh_column_async(&#34;embedding&#34;); job.wait()` completes,
and the old blocking `table.refresh_column(...)` raises
NotImplementedError naming refresh_column_async, On an Enterprise
connection the create-function.mdx example
`table.refresh_column_async(&#34;embedding&#34;,
gpu_class=&#34;h100&#34;, gpu_count=4, total_gpu_count=8)` is accepted
and submits a job, `test_quickstart_derived_feature_on_a_deployment`
passes against a real LanceDB Enterprise deployment
- Live validation: ⚠️ inconclusive - 4 of 7 scenarios driven live
against the product

| Scenario | Result | Live | Evidence |
| --- | --- | --- | --- |
| Reader opens the six changed docs pages in the local Mintlify preview
and sees the job form (`refresh_column_async` + `job.wait()`) with no
blocking `table.refresh_column(` call left | ✅ pass | live |
Rendered-page check output (artifact &#39;Rendered docs check&#39;) and
saved HTML under
~/.no-mistakes/evidence/01M85TWQ599ZJ5NQ0DBASSFT91/rendered |
| Reader follows the new `refresh_column_async` link on the
computed-column page and lands on the &#39;Run a refresh on
Enterprise&#39; section | ✅ pass | live | Rendered add-computed-column
page links to /feature-engineering/refresh-column#async; the rendered
refresh-column page (HTTP 200) contains an element with
id=&#34;async&#34; |
| Quickstart page still renders after the Enterprise-only snippet import
was removed, and its feature step shows the job form | ✅ pass | live |
quickstart returns HTTP 200; page payload contains `job =
table.refresh_column_async(&#34;quality_score&#34;)\njob.wait()`; no
`PyQuickstartAddFeatureEnterprise` reference remains |
| Regenerating snippets from docs/web-tests/py/test_quickstart.py
reproduces the committed `PyQuickstartAddFeature` snippet | ✅ pass |
live | `mdx_snippets_gen.py` output in
~/.no-mistakes/evidence/01M85TWQ599ZJ5NQ0DBASSFT91/snippets-regen/quickstart.mdx
is identical to docs/web/snippets/quickstart.mdx for that export |
| On an Enterprise connection (localhost emulator, synthetic responses)
the documented `job = table.refresh_column_async(&#34;embedding&#34;);
job.wait()` completes, and the old blocking `table.refresh_column(.… |
⏸️ untested | no | Needs the Python SDK built from this worktree. `uv
run ... maturin develop` started from a cold cargo cache and was still
compiling after about 18 minutes, so I stopped it to stay inside the
30-minute… |
| On an Enterprise connection the create-function.mdx example
`table.refresh_column_async(&#34;embedding&#34;,
gpu_class=&#34;h100&#34;, gpu_count=4, total_gpu_count=8)` is accepted
and submits a job | ⏸️ untested | no | Blocked by the same unfinished
SDK build. The source suggests this call would raise TypeError (see
finding), but that was not executed. |
| `test_quickstart_derived_feature_on_a_deployment` passes against a
real LanceDB Enterprise deployment | ⏸️ untested | no | The test skips
unless LANCEDB_DOCS_TEST_DEPLOYMENT=1 and LANCEDB_URI,
LANCEDB_HOST_OVERRIDE and LANCEDB_API_KEY point at a deployment with a
Function catalog; a localhost emulator cannot stand in for… |

- <code>`cd docs/web &amp;&amp; mint dev --port 3391 --no-open`, then
`curl http://localhost:3391/&lt;page&gt;` for quickstart,
curation/vend-secret, curation/create-function, enterprise/auto-refresh,
feature-engineering/add-computed-column,
feature-engineering/refresh-column (all HTTP 200), with a text check of
each rendered page</code>
- <code>`python3 docs/web-tests/mdx_snippets_gen.py -s docs/web-tests/py
-s docs/web-tests/ts -s docs/web-tests/rs -o
&lt;evidence&gt;/snippets-regen`, then diff of `PyQuickstartAddFeature`
against `docs/web/snippets/quickstart.mdx`</code>
- <code>`cd python &amp;&amp; uv run --extra tests --extra dev maturin
develop --extras tests,dev` (started, not finished within budget,
stopped; no result)</code>
- <code>`chrome-devtools-axi` screenshots of the rendered pages (failed:
BRIDGE_NOT_READY)</code>
- <code>Source read of `python/python/lancedb/remote/table.py`
`refresh_column_async` signature against the create-function.mdx example
(not live)</code>

🔧 Fix applied.
2 infos still open:

- ℹ️ No screenshots of the rendered docs pages were captured.
`chrome-devtools-axi` failed with &#34;Bridge failed to start within
30s&#34; and headless Google Chrome hung until killed at 60s per page.
The pages were instead fetched as served HTML from a local `mint dev`
preview and saved under rendered-round2/. For the quickstart page the
job-form snippet is present only in the page&#39;s hydration payload,
not as rendered text, so its on-screen appearance was not seen.
- ℹ️ `docs/web-tests/py/test_quickstart.py:347` -
`test_quickstart_derived_feature_on_a_deployment`, the only test that
runs the changed quickstart snippet end to end, skips because no
Enterprise deployment credentials exist (LANCEDB_DOCS_TEST_DEPLOYMENT,
LANCEDB_URI, LANCEDB_HOST_OVERRIDE, LANCEDB_API_KEY). The same calls
were driven against a localhost emulator instead, which does not prove
real-deployment behaviour.
- Live validation: ✅ go - 7 of 9 scenarios driven live against the
product

| Scenario | Result | Live | Evidence |
| --- | --- | --- | --- |
| On an Enterprise connection (Python SDK, localhost emulator, synthetic
responses) the documented `job =
table.refresh_column_async(&#34;embedding&#34;); job.wait()` submits a
refresh job and returns its resul… | ✅ pass | live |
driver-output-round2.txt: OK -&gt; rows_assigned=3 ...; server received
POST /v1/table/test/backfill_column {&#39;column&#39;:
&#39;embedding&#39;} |
| Adversarial: on the same Enterprise connection the old blocking
`table.refresh_column(&#34;embedding&#34;)` fails with
NotImplementedError naming refresh_column_async and sends no request | ✅
pass | live | driver-output-round2.txt: RAISED NotImplementedError: ...
use refresh_column_async and wait on the returned handle; requests sent:
[] |
| The create-function.mdx refresh example as now written,
`refresh_column_async(&#34;embedding&#34;, gpu_class=&#34;h100&#34;,
total_gpu_count=8)` then `job.wait()`, is accepted on Enterprise and
sends both GPU options | ✅ pass | live | driver-output-round2.txt:
server received {&#39;gpu_class&#39;: &#39;h100&#39;,
&#39;total_gpu_count&#39;: 8, &#39;column&#39;: &#39;embedding&#39;} |
| The create-function.mdx `table.add_columns({&#34;embedding&#34;:
&lt;Function binding&gt;}, total_gpu_count=8)` is accepted on Enterprise
and sends the fleet GPU ceiling | ✅ pass | live |
driver-output-round2.txt: OK -&gt; AddColumnsResult(version=2); POST
/v1/table/test/add_columns/ body carries the Function binding and
&#39;total_gpu_count&#39;: 8 |
| Adversarial: the GPU arguments removed from the create-function.mdx
example (`gpu_count` on refresh_column_async; `gpu_class`/`gpu_count` on
add_columns) are rejected by the Enterprise table, matching… | ✅ pass |
live | driver-output-round2.txt: TypeError unexpected keyword argument
&#39;gpu_count&#39; (refresh_column_async) and &#39;gpu_class&#39;
(add_columns) |
| The committed `PyQuickstartAddFeature` snippet equals what the snippet
generator produces from docs/web-tests/py/test_quickstart.py | ✅ pass |
live | `mdx_snippets_gen.py` output in snippets-regen-round2; `diff -r`
against docs/web/snippets reports no difference for quickstart.mdx |
| A reader opening the five changed pages in a local Mintlify preview
sees the job form and no blocking `table.refresh_column(` call | ✅ pass
| live | rendered-round2-counts.txt and rendered-round2/*.html: all five
pages return 200 with zero blocking calls; job form present on each |
| `test_quickstart_derived_feature_on_a_deployment` passes against a
real LanceDB Enterprise deployment | ⏸️ untested | no | Ran the test; it
skips because no Enterprise deployment credentials exist here. A
localhost emulator cannot stand in: the test registers a Function over
Flight SQL and computes real values. To run it,… |
| `version = db.create_function(embed)` from the create-function.mdx
example registers a Function on Enterprise | ⏸️ untested | no | Tried it
against the emulator; the call goes over Flight SQL to a Function
catalog, which only a real Enterprise deployment provides. This line is
unchanged by the diff. Needs the same deployment cred… |

- <code>`~/.treehouse/lancedb-9ea8c9/1/lancedb/python/.venv/bin/python
drive_enterprise_refresh_v3.py` (lancedb 0.42.0b26 built at cb082c08,
whose SDK source is identical to this head; Enterprise connection to a
localhost emulator with synthetic responses)</code>
- <code>`python docs/web-tests/mdx_snippets_gen.py -s docs/web-tests/py
-s docs/web-tests/ts -s docs/web-tests/rs -o
&lt;evidence&gt;/snippets-regen-round2` then `diff -r` against
`docs/web/snippets` (quickstart.mdx identical)</code>
- <code>`cd docs/web-tests/py &amp;&amp; python -m pytest
test_quickstart.py -q -rs` (4 passed, 6 skipped; all skips are
deployment-only tests)</code>
- <code>`mint dev --port 3397` in docs/web, then `curl` of /quickstart,
/curation/vend-secret, /curation/create-function,
/enterprise/auto-refresh, /feature-engineering/add-computed-column (all
200) and a count of blocking vs job-form calls in the served HTML</code>
- <code>`git status --short` after teardown (clean; preview stopped,
port 3397 free)</code>
</details>

<details>
<summary>✅ **Document** - passed</summary>

✅ No issues found.
</details>

<details>
<summary>⚠️ **Lint** - 1 info</summary>

- ℹ️ `docs/web-tests/py/test_quickstart.py:29` - `ruff check` reports
C408 (`dict()` call, rewrite as a literal) in the `deployment` fixture.
It is on a line this change did not touch and is also present at the
base commit; ruff&#39;s only fix for it is marked unsafe, so I left it.
`ruff format --check` passes. ruff is not on PATH, so I ran it through
`uvx`, which may not be the repo-pinned version.
</details>

<details>
<summary>✅ **Push** - passed</summary>

✅ No issues found.
</details>
2026-11-24 09:31:06 -08:00

581 lines
25 KiB
Plaintext

---
title: "Create a Function"
tag: "Early access"
sidebarTitle: "Create Function"
description: "Register Python as a column: CPU, GPU, and remote-service Functions, called once per row or once per batch."
icon: code
keywords: ["function", "udf", "cpu", "gpu", "batch", "scalar", "blob", "remote api", "embedding", "rate limiter"]
availability:
embedded: unavailable
enterprise: available
---
<Badge color="purple">Early access</Badge>
Some curation steps cannot be written as a SQL expression: an embedding
model, an image decode, a call to an external service. A Function is a
Python callable registered with the database, versioned, and then applied as
a column or called in a query -- the code runs where the data is, not pulled
into your process first. This page covers how to shape one; later curation
tasks such as [Chunking](/curation/chunking) assume you have read it. The
full registration, listing, refresh and drop lifecycle is covered on the
[Function management reference](/management/function); the examples below
focus on shaping a Function for common curation tasks.
## Scalar: once per row {#scalar}
The plain form takes one row's values and returns one result. Types are
inferred from the annotations:
<CodeGroup>
```python Python icon="python"
from lancedb import function
@function(pip=["numpy==2.2.0"])
def score(value: float) -> float:
return value * 2
version = db.create_function_async(score).wait()
table.add_columns({"doubled": version(value=col("value"))})
```
</CodeGroup>
`pip` declares the worker's dependencies; they are part of the function's
immutable version, so changing one produces a new version rather than
altering rows a previous version already filled.
## Supported Function signatures {#signature-types}
A table's [Arrow schema](/sql/data-types#supported) can contain types that a
Function cannot accept or return. The matrix below describes the Python SDK
`0.42.0-beta.12` source contract. Nested schemas and list-Blob outputs require
a matching Enterprise server; an SDK upgrade alone does not enable them.
| Arrow type | Function input/output support |
| --- | --- |
| Boolean; signed/unsigned 8, 16, 32, 64-bit integers; float16/32/64 | Supported. Ordinary `int` and `float` annotations infer int64 and float64. |
| utf8 / large_utf8; binary / large_binary | Supported. `str` and `bytes` infer utf8 and binary. Plain binary does not carry Blob semantics. |
| date32 / date64 | Supported; Python `date` infers date32. |
| timestamp, with or without timezone; time32/64; duration; interval | Unsupported by the Function signature grammar. A Python `datetime` annotation can resolve to an Arrow timestamp but registration still rejects it. |
| decimal; map; dictionary; union; fixed-size binary | Unsupported. Decode dictionary values and use supported scalar/list/struct representations. |
| struct; list / large_list; positive-length fixed-size list | Supported with supported children. Explicit schemas preserve child nullability; annotation-only `list[T]` uses non-nullable elements. Struct fields must be nonempty and uniquely named. |
| Blob v2 at top level or in a struct | Supported in inputs and outputs; use `lancedb.blob(...)` in the schema. |
| Blob v2 under list / large_list | Output only on supporting SDK/server versions. Inputs are rejected. |
| Blob v2 under fixed-size list or map | Unsupported in both directions. |
For times, pass an int64 epoch value with an explicit unit such as microseconds,
or a UTF-8 ISO 8601 string with its timezone. Convert inside the Function and
cast the result in SQL if needed. Use scaled integers with a declared scale
when exact decimal values matter; converting to float can lose precision.
Represent a map as a list of key/value structs when that fits the calculation.
A scalar output is non-nullable because physical NULL represents an unfilled
computed output. For an optional value, return a named struct with a nullable
field, for example:
```python
import pyarrow as pa
from lancedb import function
@function(
input_schema=pa.schema([pa.field("text", pa.string(), nullable=False)]),
output_schema=pa.schema([pa.field("score", pa.float64(), nullable=True)]),
)
def optional_score(text: str):
return {"score": float(len(text)) if text else None}
```
Return a dictionary by field name. A successfully computed nullable field can
be NULL; `score IS NULL` alone cannot distinguish it from pending work or a
skipped failure. Use the job result and error diagnostics. Do not assume an
explicit assignment-state flag is available on every deployment.
List-nested Blob outputs are queryable as descriptors, but row-ID blob fetch
APIs and `blob_mode="bytes"` do not fetch payloads inside lists. Prefer a
separate row per media item when you need independent reads, retries or
re-scoring. A plain struct shaped like a Blob without its extension metadata
is not a substitute for `lancedb.blob`.
## Batch: once per call, many rows at a time {#batch}
A function is called once per batch instead of once per row when all of its
parameters are annotated `pyarrow.Array`. Those annotations say that a whole
column arrives in one call, but not which Arrow type the column holds, so a
batch function also passes `input_schema` and `output_schema`; every field of
`input_schema` matches a parameter by name and by order. The same doubling
logic, vectorized over a whole batch at once:
<CodeGroup>
```python Python icon="python"
import pyarrow as pa
import pyarrow.compute as pc
from lancedb import function
@function(
pip=["numpy==2.2.0"],
input_schema=pa.schema([pa.field("value", pa.float64(), nullable=False)]),
output_schema=pa.float64(),
batch_size=32,
max_concurrency=4,
row_timeout_seconds=90,
)
def score_batch(value: pa.Array) -> pa.Array:
return pc.multiply(value, 2)
```
</CodeGroup>
Read several columns in one call by taking one `pa.Array` parameter per
column, with one schema field for each:
```python
@function(
input_schema=pa.schema([
pa.field("value", pa.float64(), nullable=False),
pa.field("weight", pa.float64(), nullable=False),
]),
output_schema=pa.float64(),
)
def weighted_score(value: pa.Array, weight: pa.Array) -> pa.Array:
return pc.multiply(value, weight)
```
A single `pyarrow.RecordBatch` parameter is also a batch function, but it does
not read several columns at once: `input_schema` declares one field per
parameter, so a `RecordBatch` parameter binds one input column and receives
that column as a batch. A schema with more fields than the callable has
parameters is rejected at decoration.
Batching amortizes per-call overhead across many rows, which matters most
once a function also does something with real fixed cost per call -- loading
a model, opening a connection, making a network round trip.
`batch_size` caps the number of input rows in each execution batch; actual
batches may be smaller. `max_concurrency` limits user-code calls in flight for
one Function within one logical execution; it does not limit calls across
different jobs and is not an account-wide quota. `row_timeout_seconds` bounds
each Python call: one row for scalar Functions or the entire batch for
vectorized Functions. It does not include the instance's `__init__`. These
settings are fixed into the registered version and apply to direct calls,
computed columns, and materialized-view refreshes alike. A refresh can
override `max_concurrency` for that execution. Omit it to preserve the
existing behavior.
## Stateful Functions: load once, call many times {#stateful}
A `@function`-decorated **class** is the same callable with state. Each remote
instance calls `__init__` once, calls `__call__` for every row or batch it
processes, and calls `close()`, if defined, once when it retires:
<CodeGroup>
```python Python icon="python"
from lancedb import function
@function
class scale:
def __init__(self, factor: float, offset: float = 0.0):
self.factor = factor
self.offset = offset
def __call__(self, value: float) -> float:
return value * self.factor + self.offset
```
</CodeGroup>
Constructor parameters are **initialization fields**, bound once per binding
rather than read per row -- mixed with per-row columns in the same call:
`version(value=col("value"), factor=2.0)`. Load models, open clients, and
build rate limiters in `__init__`; every batch the instance serves then
reuses them, since an instance's state is shared across its own batches but
never across other instances or workers. This is the pattern GPU inference
and remote-API Functions both build on below.
## GPU: batch inference, loaded once {#gpu}
`db.list_gpu_classes()` lists the GPU classes configured for the deployment.
Each record reports the operator's hardware description and limits; it does
not mean a GPU is currently free. Listing requires the System Usage
permission. Pass a returned class name to `gpu_class`, such as `gpu=True, gpu_class="a10g", gpu_count=2`,
to select a pool; `gpu_count` controls the GPUs allocated together to each worker.
`gpu_count` defaults to one. Omitting `gpu` uses CPU workers:
<CodeGroup>
```python Python icon="python"
import pyarrow as pa
from lancedb import function
gpu_class = next(
gpu.name for gpu in db.list_gpu_classes() if gpu.gpu_model == "NVIDIA A10G"
)
@function(
gpu=True,
gpu_class=gpu_class,
row_timeout_seconds=600,
pip=["torch==2.12.0", "sentence-transformers==5.7.0"],
input_schema=pa.schema([pa.field("text", pa.string(), nullable=True)]),
output_schema=pa.list_(pa.float32(), 384),
)
class embed_text:
def __init__(self, model_name: str = "all-MiniLM-L6-v2"):
import torch
from sentence_transformers import SentenceTransformer
device = "cuda" if torch.cuda.is_available() else "cpu"
self.model = SentenceTransformer(model_name, device=device)
def __call__(self, text: pa.Array) -> pa.Array:
texts = [t or "" for t in text.to_pylist()]
embeddings = self.model.encode(texts)
return pa.array(embeddings.tolist(), type=pa.list_(pa.float32(), list_size=384))
version = db.create_function_async(embed_text).wait()
table.add_columns({"embedding": version(text=col("caption"))})
```
</CodeGroup>
`row_timeout_seconds` sets the per-call deadline, not the `__init__` budget.
Current Enterprise builds default to 300 seconds for both CPU and GPU
Functions. Enterprise 1.13.0 through 1.14.1, and 1.15.0 builds before the
shared default was restored, reject a GPU refresh unless the Function
definition or the refresh request sets a positive value; registration still
succeeds. A refresh value overrides the definition. Size the deadline from the
longest observed call. The 600 seconds above is one working GPU example, not a
universal recommendation.
Older servers that do not implement `GET /v1/gpu/classes` raise
`NotImplementedError`. With `gpu=True`, omitting `gpu_class` accepts any
eligible configured class, equivalent to `gpu_class="any"`. Use
`gpu_class="default"` to request the default pool explicitly. Class names
must be lowercase. Counts
must be positive integers; the deployment must have a node that can supply
that many devices together. `max_gpu_count_per_worker` in the class inventory
is the operator's cap; an unset cap does not promise unlimited hardware.
Use `gpu=True, gpu_class="any", gpu_count=2` when any configured GPU class is acceptable, but each
worker needs two devices together. `gpu=True, gpu_class="any"` requests one GPU. The server
selects a class that fits the request using operator-configured limits,
preferring known multi-GPU limits over unspecified limits. The selected
class is fixed for the worker cohort; selection does not reserve capacity
until the worker is scheduled. `gpu=True, gpu_count=2` makes the same request
as `gpu=True, gpu_class="any", gpu_count=2`. A Function with an `any` request
can share a SQL job with a
Function pinned to a class; that job uses the pinned class.
The request is immutable with the Function version. Configure tensor
parallelism in the model separately, for example vLLM's
`tensor_parallel_size=2` for `gpu=True, gpu_class="a10g", gpu_count=2`.
The refresh `total_gpu_count` is a separate aggregate budget across workers and
must be at least the Function's per-worker count. Set it through
[`refresh_column_async`](/feature-engineering/refresh-column#resources).
The model loads once per worker instance, in `__init__`; `__call__` only
encodes the batch it was handed. Registering the same logic as a plain
function instead would reload the model on every single row.
## Calling a remote service {#remote}
A function that calls an external API needs a credential without putting it
in the function's source. A Secret is a database-scoped named credential:
`db.create_secret` stores the value once, and binding it at registration time
puts it in the environment variable the function reads, without ever
returning it from any API or recording it in the function's own definition.
Combine it with the stateful form so the HTTP client -- and any rate limiter
around it -- is built once, not reopened on every row. Configure HTTP timeouts
inside `__call__`. Refresh-level `error_policy='skip'` can record row failures;
see [handling failures](/management/function#failures). Native retry policies
need matching SDK, server and Function-image support; on other deployments,
handle bounded retries inside the Function only when repeating the request is
safe.
See [Vend a Secret to a Function](/curation/vend-secret#specify) for the
full worked example, how the bound value actually reaches a running
evaluation, and how that differs from rotating or revoking it later.
## Read and produce blobs {#blobs}
A Function can bind a [Blob v2 column](/management/table#managed-blobs) and
return a Blob v2 value at the top level or inside a struct. In row mode, a
top-level blob parameter arrives as Python `bytes`, or `None` for a nullable
input, after the worker reads the payload. Use `BlobReader` to read it
incrementally.
This section extracts a frame from a stored video and captions it,
continuing as one example across chaining, persisting and incremental reads
below. `videos` holds raw clips in a `video` Blob v2 column; `frames` names
one timestamp per clip to extract, with a `selected` flag to skip some:
<CodeGroup>
```python Python icon="python"
import pyarrow as pa
videos = db.create_table("videos", schema=pa.schema([
pa.field("id", pa.utf8(), nullable=False),
lancedb.blob("video", nullable=False),
]))
frames = db.create_table("frames", [
{"frame_id": 1, "video_id": "clip-1", "ts": 0.5, "selected": True},
{"frame_id": 2, "video_id": "clip-1", "ts": 1.5, "selected": True},
])
```
</CodeGroup>
### Produce a blob {#produce-blobs}
{/*
Draft for the streaming Blob output release.
Use `BlobWriter` during computed column refresh to produce a Blob v2 value in
chunks. Register the Function with a Python SDK that exposes `BlobWriter`
after upgrading the LanceDB Enterprise server and Function worker images to
versions that support streaming Blob output. Keep returning `bytes` with an
explicit Blob v2 output schema on deployments without writer support.
Import `BlobWriter` from `lancedb.functions`. In a scalar Function,
`-> BlobWriter` infers a non-nullable Blob v2 output. For a vectorized
Function, provide `input_schema` and annotate the return as
`list[BlobWriter]` or `tuple[BlobWriter, ...]` to infer one Blob v2 result per
row. Return the writers in input row order. Use `BlobWriter.field(...)` in
an explicit output schema to mark writer-capable Blob v2 fields in named or
nested results.
Open a writer with `BlobWriter.open()`, pass each chunk to `write()`, and
return the sealed writer after leaving its context manager. For plain SQL
`SELECT`, use a byte-returning Function within the query's Arrow output
limits.
*/}
`extract_frame` reads one frame from a video and returns JPEG bytes. Its
explicit output schema declares a Blob v2 result. The `BlobReader` input
lets it read the video incrementally. [Read a blob incrementally](#incremental)
<CodeGroup>
```python Python icon="python"
from datetime import timedelta
from lancedb import BlobReader, col
from lancedb.functions import function
@function(
name="extract_frame",
gpu=True,
pip=["av==13.1.0", "pillow==11.0.0"],
input_schema=pa.schema([
lancedb.blob("video"),
pa.field("ts", pa.float64(), nullable=False),
]),
output_schema=lancedb.blob("jpeg", nullable=False),
)
def extract_frame(video: BlobReader, ts: float) -> bytes:
... # decode the frame at ts, encode as JPEG, return its bytes
extract_frame_version = db.create_function_async(extract_frame).wait(
timeout=timedelta(minutes=15)
)
```
</CodeGroup>
An empty byte string is a filled result. A top-level Blob v2 output cannot be
nullable; to return a nullable blob as a value, use a named-struct output
schema with a nullable blob field. The struct itself records whether the
result has been filled. A nullable non-Blob scalar output is declared with
`Optional[T]` or `T | None`; see [Functions](/management/function#define).
Read a nested blob with `table.fetch_blobs("payload.image", hits)`.
A list or large-list output may also contain Blob v2 elements; inputs and
fixed-size lists do not support this layout. List-nested values are queryable
as descriptors, but `fetch_blobs` and `blob_mode="bytes"` cannot fetch their
payloads.
A bare `bytes` return annotation infers ordinary Arrow `binary`. To store
returned bytes as Blob v2, declare `output_schema=lancedb.blob(...)`.
### Chain a Function on its output {#chain}
A second Function can bind a blob another Function produced. Register
`caption` the same way, consuming a blob instead of producing one:
<CodeGroup>
```python Python icon="python"
@function(gpu=True, pip=["transformers==4.47.0"])
def caption(jpeg: bytes) -> str:
... # run a vision-language model over the JPEG, return one sentence
caption_version = db.create_function_async(caption).wait(timeout=timedelta(minutes=15))
```
</CodeGroup>
Compose both in one SQL statement over a join, instead of applying each as
its own column. The join supplies `video` and `ts` from two different
tables, and `caption` reads `extract_frame`'s result as it is computed,
before anything is written:
<CodeGroup>
```sql SQL
SELECT f.frame_id, extract_frame(v.video, f.ts) AS jpeg,
caption(extract_frame(v.video, f.ts)) AS caption
FROM videos v JOIN frames f ON v.id = f.video_id
WHERE f.selected = true
```
</CodeGroup>
[`EXPLAIN`](/sql/dql/explain) on a query like this shows `RemoteTake`: the
blob is read once, where the worker runs, and never pulled into the query
node first.
### Persist it as a column, or a materialized view {#persist}
Apply the same registered version with `add_columns` to persist its output as
an ordinary table column, on a table that already has both of its inputs --
here, a single-clip table with its own `video` and `ts`, rather than the two
tables the join above reads from:
<CodeGroup>
```python Python icon="python"
clips = db.create_table("clips", schema=pa.schema([
pa.field("frame_id", pa.int64(), nullable=False),
lancedb.blob("video", nullable=False),
pa.field("ts", pa.float64(), nullable=False),
]))
clips.add_columns({"jpeg": extract_frame_version(video=col("video"), ts=col("ts"))})
result = clips.refresh_column_async("jpeg").wait(timeout=timedelta(minutes=15))
assert result.rows_failed == 0
hits = clips.search().select(["frame_id", "jpeg"]).with_row_id(True).to_arrow()
values = clips.fetch_blobs("jpeg", hits).to_pylist()
```
</CodeGroup>
Or wrap the join and both Functions in a
[materialized view](/sql/ddl/materialized-view) instead, so the extracted
frame and its caption stay current as new videos and frames arrive. See
[Auto Refresh](/enterprise/auto-refresh) for
keeping either one fresh without calling refresh yourself.
On deployments that support computed-column inputs, another Function can
bind to `col("jpeg")` directly, the same as the SQL join above does through
its own expression. Refresh the producer first, then the consumer. Once
outputs are current, a later refresh fills appended rows. A filtered
refresh preserves payload references for unselected Managed outputs. An
unfiltered refresh can recompute a whole fragment when it cannot establish
that the fragment's outputs are current.
Function output blobs follow the same compaction and cleanup lifecycle as
ingested Managed blobs. Retained versions continue to own their payloads;
cleanup reclaims an object only after its retained references are gone.
### Read a blob incrementally {#incremental}
Annotate a row Function parameter with `BlobReader` to read a Blob v2 input
incrementally, the way `extract_frame` above does, instead of materializing
the whole payload first. The signature selects the access mode without
another registration option. A minimal example, reading only the first MP4
box type without loading the rest of the video:
<CodeGroup>
```python Python icon="python"
from lancedb import BlobReader, function
@function
def first_box_type(video: BlobReader) -> bytes:
video.seek(4)
return video.read(4)
```
</CodeGroup>
The worker passes a seekable reader backed by the stored blob --
`video.seekable()` is `True`. `read(size)` reads from the current cursor;
`read_range(offset, length)` reads a byte range without moving it, the same
bytes a `seek(offset)` followed by `read(length)` would read. `size()`
returns the payload size without reading it. Each row call receives its own
reader, which closes when the call returns or raises. Do not retain it for
another invocation.
Use `video: bytes` when the Function needs the complete payload. Bytes inputs
materialize before invocation and remain subject to eager input limits.
Reader inputs keep the unread payload out of the input batch, but calling
`video.read()` without a size loads all remaining bytes in Python. Reader
inputs are supported in row mode. Return values remain ordinary values such
as `bytes`; this feature does not add streamed outputs.
## What to read next {#next}
<CardGroup cols={2}>
<Card title="Function" icon="code" href="/management/function">
List, describe and drop registered Function versions.
</Card>
<Card title="Vend a Secret to a Function" icon="key" href="/curation/vend-secret">
Bind a credential by reference instead of putting it in the function's source.
</Card>
<Card title="Chunk records into multiple rows" icon="diagram-subtask" href="/curation/chunking">
A Function whose output is a list, exploded into one row per element.
</Card>
<Card title="Refresh a computed column" icon="arrows-rotate" href="/feature-engineering/refresh-column">
Filling the column a Function is bound to, and re-filling it as inputs change.
</Card>
</CardGroup>
## Default execution budgets
`total_cpu_millis`, `total_memory_bytes`, and
`total_gpu_count` supply execution-wide defaults. CPU is in millicores
(1000 = one core), memory is in bytes, and GPU count is a total across workers.
All five resource settings use the same names at registration, creation, and
refresh. Each resolves independently in this order:
1. The refresh's value.
2. The column or materialized view's value.
3. The registered Function's value.
4. The deployment default for total budgets and device count; any eligible
configured GPU class when no layer specifies one.
For a materialized view using multiple Functions, the third layer adds the
`total_*` budgets across distinct pinned Function versions. Its per-worker GPU
count uses the largest Function default, and GPU classes must be compatible
unless the declaration or refresh overrides the class. Calling the same version
more than once counts it once. Column and view defaults also apply when the
service schedules a refresh automatically. Integer overflow or a budget that
cannot fit a required worker is rejected.
```python
@function(
gpu=True,
gpu_class="h100",
gpu_count=2,
total_cpu_millis=8000,
total_memory_bytes=16 * 1024**3,
total_gpu_count=4,
)
def embed(text: str) -> list[float]: ...
version = db.create_function(embed)
table.add_columns(
{"embedding": version(text=col("text"))},
total_gpu_count=8,
)
job = table.refresh_column_async(
"embedding", gpu_class="h100", total_gpu_count=8
)
job.wait()
db.create_materialized_view(
"embeddings", query="SELECT embed(text) AS embedding FROM documents",
total_cpu_millis=16000,
gpu_class="any",
gpu_count=2,
total_gpu_count=8,
)
```
`gpu_class` selects the GPU pool and `gpu_count` selects the positive number
of devices allocated together to each worker. Both can be overridden at
column/MV creation and refresh. On LanceDB Enterprise, the Python
`add_columns` does not yet accept `gpu_class` or `gpu_count`, and
`refresh_column_async` does not yet accept `gpu_count`; those values come from
the registered Function. An explicit `gpu_class="any"` replaces a
registered class with any eligible configured pool. These settings require a
GPU Function for computed columns. The `total_*` values are ceilings for the
whole worker fleet. CPU and memory can limit the fleet before it reaches its GPU ceiling.