Enterprise only Early access
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 assume you have read it. The
full registration, listing, refresh and drop lifecycle is covered on the
Function management reference; the examples below
focus on shaping a Function for common curation tasks.
Scalar: once per row
The plain form takes one row’s values and returns one result. Types are inferred from the annotations: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
A table’s Arrow schema can contain types that a Function cannot accept or return. The matrix below describes the Python SDK0.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.
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:
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
A function is called once per batch instead of once per row when all of its parameters are annotatedpyarrow.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:
pa.Array parameter per
column, with one schema field for each:
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
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:
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
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:
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.
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
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. 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 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
A Function can bind a Blob v2 column and return a Blob v2 value at the top level or inside a struct. In row mode, a top-level blob parameter arrives as Pythonbytes, 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:
Produce a blob
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
Optional[T] or T | None; see Functions.
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
A second Function can bind a blob another Function produced. Registercaption the same way, consuming a blob instead of producing one:
video and ts from two different
tables, and caption reads extract_frame’s result as it is computed,
before anything is written:
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
Apply the same registered version withadd_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:
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
Annotate a row Function parameter withBlobReader 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:
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
Function
List, describe and drop registered Function versions.
Vend a Secret to a Function
Bind a credential by reference instead of putting it in the function’s source.
Chunk records into multiple rows
A Function whose output is a list, exploded into one row per element.
Refresh a computed column
Filling the column a Function is bound to, and re-filling it as inputs change.
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:
- The refresh’s value.
- The column or materialized view’s value.
- The registered Function’s value.
- The deployment default for total budgets and device count; any eligible configured GPU class when no layer specifies one.
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.
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.