Reference
Functions reference
The full Function reference: declaration rules, AI decisions and model roles, access modes and who is calling, client addresses, share links, and publication detail.
This page is the full reference for Functions. For a short introduction with examples, read Functions first.
DeclarationLink to this section
A function lives at functions/<slug>/function.py in a Workspace. Its capabilities are inferred statically from the source: there are no .limilake/ sidecar files. A function can expose:
- an action (
@fn.action): a callable operation, - HTTP routes: a public function data plane endpoint,
- a sync (
@fn.sync): DuckLake-native ingestion, - a schedule (
schedule=on the factory): durable cron runs.
A scheduled function whose body calls agent.run() is also how you run an agent on a schedule: there is no separate agent scheduler. See limilake docs agents.
limilake add function follows the Workspace Contract in limilake.toml.
Contract v2 generates the durable id; preserve it when moving or editing the
Function, and generate a new ID when copying the Function into a new item.
Contract v1 does not define id, so its compatibility scaffold omits that
keyword. Use limilake workspace migrate to add durable identities and advance
an initialized Contract v1 Workspace to v2. name is its human-readable label.
description explains what the
Function does to people and agents; for an MCP-exposed Function, it is also the
first paragraph of the projected tool description. Keep it short, specific, and
current.
Inside an except block, use logger.exception("daily report failed") to log
the message together with the current exception traceback. Use logger.error
when there is no active exception to attach.
An action or sync declares either no parameter, or one required
dict[str, T] parameter. LimiLake delivers the complete run input JSON object
as that one argument; object fields are not mapped onto Python parameters by
name. Scalar parameters, multiple parameters, and parameter defaults are
invalid. A zero-parameter handler ignores the input object.
Managed delivery populates the governed runtime before your code runs. During
limilake dev, a deliberate local action instead starts without platform
authority: logger works immediately, while lake, AI, Connection, Document,
Secret, and Agent capabilities bootstrap when your code first uses them. Keep
governed module attributes such as limilake.lake inside the handler so the
module can be imported before that capability is needed. Without an available
CLI session, first use fails the local run with the actionable
capability_unavailable error.
There is no def run(ctx): wrapper and no manual import of credentials. Data
access is scoped by the function's mounts, and providers are reached through
limilake.connections (the egress gateway), never as raw secrets. Lazy local
bootstrap changes when authority is acquired; the platform still authorizes
every governed operation live.
DecisionsLink to this section
limilake.ai.decide asks typed questions about a piece of state and returns
typed answers in one call. Requests name the systemone decision role, not a
model: the platform maps the role to its current decision model, and each
result reports the model that answered in model (None when the response
did not name one).
import limilake
@fn.action
def triage(payload: dict[str, str]) -> dict[str, object]:
ticket = {"subject": payload["subject"], "body": payload["body"]}
team = limilake.ai.decide.choice(
ticket,
"Which team should handle this ticket?",
{"billing": "Invoices and payments", "support": "Product problems"},
)
urgency = limilake.ai.decide.score(
ticket, "How urgent is this ticket?", ["can wait", "this week", "today"]
)
refund = limilake.ai.decide.noul(ticket, "The customer asks for a refund.")
return {
"team": team.answer.choice,
"urgency": urgency.answer.score,
"refund": refund.answer.noul > 0.5,
}choice(state, instructions, criteria)picks one key ofcriteria(option name to description). The answer carries per-optionprobabilitiesand aconfidencewhen the model reports them. A choice outsidecriteria, or a probability or confidence outside 0 to 1, raisesLakeProxyError.score(state, instructions, levels)places the state on ordered levels, lowest first.answer.scoreruns from0(the first level) upward, andanswer.legendmaps level keys back to your levels.noul(state, instructions, criteria=None)returns the probability, from 0 to 1, that the statement ininstructionsis true. The optionalcriteriadescribes what"true"and"false"mean.ask(state, questions)sends several questions in one call.questionsmaps your own ids to{"type": ..., "instructions": ..., "criteria": ...}objects, and the result'sanswersuses the same ids.
state, instructions, and criteria accept a string or any JSON value. Every
question of a successful call counts as one decision against the Tenant's
monthly decision:systemone package, and a request carries at most 512
questions in a body of at most 1 MiB. Invalid questions raise ValueError before a
request is sent. Gateway refusals raise LakeProxyError with the gateway
status and code: 402 for billing, 403 when the resource is not allowed,
and 429 for limits.
Model roles and rerankingLink to this section
The generation, extraction, embedding, and search helpers default to model
roles. The defaults are standard for limilake.extract(...) and the
other generation helpers, and embed-1024 for limilake.embed(...) and
limilake.search(...). Pass model="frontier" for the highest-quality hosted
model or model="embed-3072" for text-embedding-3-large vectors. A concrete
model name you pass is still accepted, and transcription keeps its
kb-whisper-large default. model="ultrafast" names the lowest-latency hosted
model; it carries a small allowance on every plan (20 requests and 100,000
tokens a minute, 2 concurrent requests, 2,000,000 tokens a month) and answers
429 beyond it. model="light" names a light, fast hosted model for agent
loops and structured output, with the same plan limits as frontier.
The platform maps a generation role to its current model, so a model upgrade
needs no code change. An embedding role never changes model, because a new
model would make every stored vector incomparable. embed-1024 always returns
1024-dimension vectors from qwen3-embedding-0.6b, the same vectors as that
model name, and refuses a dimensions other than 1024 with 400; omit it or
pass 1024. embed-3072 returns text-embedding-3-large vectors with 3072
dimensions by default, and fewer when you pass a smaller dimensions; vectors
of different sizes never compare, so store the dimensions you embedded with.
A new embedding model ships as a new versioned role, such as embed-1024-v2,
and stored vectors are re-embedded before a Function switches to it. Vectors
from different embedding roles never compare with each other.
limilake.ai.rerank(query, documents, top_n=None) ranks documents by relevance
to a query with the rerank role and returns them most relevant first:
import limilake
@fn.action
def late_fee_notes(payload: dict[str, list[str]]) -> list[dict[str, object]]:
ranked = limilake.ai.rerank("notes about late payment fees", payload["notes"], top_n=3)
return [{"note": result.document, "score": result.relevance_score} for result in ranked]Each RerankResult carries the document's index in the list you sent, its
relevance_score (higher is more relevant; compare scores only within one
call), and the document itself. A call takes 1 to 1000 strings; invalid input
raises ValueError or TypeError before a request is sent. Every document of
a successful call counts as one unit of the Tenant's monthly rerank:rerank
package, and gateway refusals raise LakeProxyError like the other AI calls.
Access and execution identityLink to this section
Functions declare two separate choices:
access="private" | "api_key" | "public"controls who may invoke it.run_as="caller" | "assigned"controls whose live authority the runtime uses.
The valid combinations are private+caller, private+assigned,
api_key+assigned, and public+assigned. Private caller mode is the default.
Caller-less access must use an assigned identity.
The first publish of a new run_as="assigned" function assigns the linked
Tenant Identity of the authenticated publisher. Git author and committer fields
are never trusted for authority. Later code pushes preserve that assignment;
an explicit reassignment or security-mode change revalidates through the same
server policy. At runtime the identity, its active Tenant User, and its
Workspace Access Level are checked live, so offboarding or a removed Membership
fails closed until the function is reassigned.
The older auth= spelling remains a deprecated compatibility alias. New code
should use access= and run_as=.
Who is callingLink to this section
limilake.caller() tells a Function which person it is serving:
import limilake
caller = limilake.caller() # limilake.Caller | None
if caller is not None:
caller.tenant_user_id # UUID, stable for this person in this Tenant
caller.display_name # "Alex Morgan" (falls back to the email)
caller.email
caller.access_level # "viewer" | "editor" | "owner" | None
caller.initials # "AM"The platform resolves the caller server-side; never decode the sandbox token
yourself. access_level is the caller's live Workspace Access Level in the
Function's Workspace: viewer, editor, or owner.
| Invocation | limilake.caller() |
|---|---|
HTTP route, run_as="caller", called by a person or from a published App | The caller |
HTTP route, run_as="caller", called by an Agent | None |
HTTP route, run_as="caller", called by another Function's code | Raises not_propagated; from a run_as="caller" Function's warm session, as for whoever called that Function (the person, or None for an Agent); never with a Run's own token |
| Run started by a person (portal, CLI, a published App, or an async request) | The person who started it |
| Run started by an Agent, interactive or scheduled | None |
| Run started by another Function's code | Raises not_propagated; started from a run_as="caller" Function's warm session, as for whoever called that Function (the person, or None for an Agent); never when started with a Run's own token |
Run of an api_key or public async request | None |
| Schedule, Agent runtime | None |
HTTP route, run_as="assigned", called by a person (portal session or PAT) | That person |
HTTP route, run_as="assigned", called from a published App | The App viewer, whatever the Function's access mode |
HTTP route, run_as="assigned", api_key or public request | None |
HTTP route, run_as="assigned", called by an Agent | None |
HTTP route, run_as="assigned", called by another Function's code | Raises not_propagated; from a run_as="caller" Function's warm session, as for whoever called that Function (the person, or None for an Agent); never with a Run's own token |
Local limilake dev | The developer, with access_level=None |
None means there is no human caller. CallerUnavailableError (its reason
is not_propagated, access_revoked, profile_unavailable, no_credential,
context_expired, rejected, or unreachable) means one may exist but is not
revealed, so refuse the write instead of attributing it to nobody.
access_revoked means the caller lost access to the Workspace after the
request was admitted. The tenant_user_id equals the viewer.tenant_user_id a
published App sees, so an App and its Functions agree on who the person is. The
caller is display and attribution data: it grants nothing, and the email it
carries is the App author's responsibility once stored or sent anywhere.
A run_as="assigned" route is one warm server shared by every caller, so each
request carries a short-lived context the platform signed for that request
alone, and caller() sends it back for the platform to verify. The route keeps
its own assigned authority, so it can record per-person data, such as a
person's own marks, for callers who may only view the Workspace. Never read or
decode that context yourself: it is signed, not encrypted, and only caller()
gets an answer the platform verified and re-checked against the person's
current access. A call from another Function's code names no caller, even when
a person called that Function, unless the calling Function runs
run_as="caller", a person called it, and its code presents its warm session's
own credential: that session belongs to that person, so it passes them on. A
run_as="caller" Function that an Agent or another Function's code called
passes on no person. Neither does a Run's own token, a run_as="caller"
Function's Run included: a call made with it raises not_propagated, and a Run
started with it records a Function as its requester. A deliberate Run's code
holds no other credential. Resolve the caller early in the handler and keep the
value: the context is valid for five minutes after the request was admitted.
Later calls in the same request reuse the first answer until then; any call
after five minutes raises context_expired. A task the handler spawns can ask
while the request runs, never after it ended.
A Run, deliberate or async (Prefer: respond-async), reports the person who
started it, from the Run's record, only when that person's own credential
started it. A Run an Agent started returns None, and a Run another Function's
code started answers exactly as a request made with the same credential would,
as the table shows. Unlike a synchronous request, a Run still reports its
person after they lose Workspace access, with access_level=None, so check
access_level before recording anything for them. The SDK presents an async
Run's token, and reuses the answer caller() gave for it, only while the Run's
request runs: a task its handler spawns that is still running after the request
ended no longer presents that token, so its caller() answers for the warm
server itself, which raises not_propagated for a run_as="assigned"
Function. An agent.start() handle, or an agent.run() still polling, made
during the request polls with the warm server's own token from then on.
These assigned-route answers are new in CLI 0.1.84 and its runtime. Before,
caller() raised not_propagated on every run_as="assigned" route. A
Function written for that now gets a person, or None for an api_key,
public, or Agent request: handle None and check whether a write you used to
refuse is now allowed. A run_as="caller" route used to report the user an
Agent runs as, or the identity another Function's code runs as, as its caller;
it now returns None for an Agent and raises not_propagated for another
Function's code, unless that code presents a run_as="caller" Function's
warm-session credential, which passes on whoever called that Function. A Run
did the same and changed the same way. A Run started before this change raises
not_propagated, because it never recorded who started it.
The client addressLink to this section
limilake.client_address() tells an HTTP route which address the request came
from, when the platform could establish one:
address = limilake.client_address() # limilake.ClientAddress | None
if address is not None:
address.ip # "203.0.113.9"
address.via # "direct" | "cloudflare" | "unverified_proxy"It is set on requests to a custom domain bound to the Function and on calls
from an App. direct means the visitor connected to LimiLake itself.
cloudflare means the domain is proxied through Cloudflare in Cloudflare edge
mode with its edge secret, and ip is the visitor from Cloudflare. With
unverified_proxy, ip is the proxy the request came through, not the
visitor. It is None on the app.limilake.com/api/functions/... URL, where
there is no address worth trusting, and outside a request. Never read
X-Forwarded-For or another request header as an address: anyone can write it.
Share linksLink to this section
limilake.shares lets someone without a LimiLake sign-in open one thing you
chose to share, such as one candidate, through a link. LimiLake mints a random
token, stores only a hash of it, and remembers the kind and subject you
gave it until it expires or you revoke it.
from datetime import timedelta
share = limilake.shares.mint("candidate", candidate_id, expires_in=timedelta(days=14))
link = f"https://share.example.com/c/{candidate_id}#t={share.token}" # token shown once
# In the public Function, with the candidate id from the request path:
found = limilake.shares.validate(token, kind="candidate", subject=candidate_id)
if found is None:
... # show nothing
limilake.shares.revoke(share.id) # one link
limilake.shares.revoke(kind="candidate", subject=candidate_id) # all of them
limilake.shares.list(kind="candidate") # never shows tokensMint from a private Function and validate in a public one: anyone can call a
public Function, so it must never mint. Pass subject to validate so a link
can only open what it was made for. max_uses=1 on mint makes a one-time
link. validate counts one use and returns None for every refusal, whether
the token is unknown, of another kind or subject, expired, revoked, used up, or
throttled. Minting, listing and revoking need editor on the Workspace and
validating needs viewer, checked for the identity the Function runs as.
Each share validates at most 60 times a minute per visitor, one visitor may
fail 20 times a minute, and a Workspace mints at most 600 shares a minute and
holds at most 100 000 live ones. Visitors are told apart by
limilake.client_address(), which the SDK sends for you; on the
app.limilake.com/api/functions/... URL there is none, so all visitors share
one budget. Past a limit on mint the SDK raises
limilake.SharesRateLimitedError. Limits reset every minute and never lock
anyone out.
A public App (access = "public", see limilake docs apps) gives each
visitor their own address, so it is the place to serve a share link page.
From the CLI, a person or an agent can grant, list, revoke and check shares without code:
limilake workspace share create --workspace=recruitment --kind=candidate --subject=cand_8f2a --expires-in=7d
limilake workspace share create --workspace=recruitment --kind=candidate --subject=cand_8f2a --max-uses=1
limilake workspace share list --workspace=recruitment --kind=candidate
limilake workspace share revoke <share-id> --workspace=recruitment
limilake workspace share validate --token-file=- --workspace=recruitment --kind=candidate --subject=cand_8f2acreate prints the token once; --max-uses=1 makes a one-time share.
validate reads the token from stdin, exits 4 when it is not valid, and counts
one use, so checking a one-time share uses it up. Add --output=json for
machine-readable output.
Publication and executionLink to this section
See Publish for the push that publishes a Function. The same push queues an exact-SHA Build; successfully built App artifacts activate automatically. Invoking the Function later creates a Function Run; it does not publish source.
limilake function commit commits named local Function files directly to a
Workspace branch. It is not a separate deployment
or activation path: with its default --branch main, the resulting accepted
revision enters the same main-indexing and exact-SHA Build flow as a Git push.
The fixed entrypoint may be written as either
functions/daily-report/function or functions/daily-report/function.py; both
address the same file. If the selected branch already contains those bytes, the
command succeeds with changed: 0 and creates no commit, indexing event, or
Build.
Run inputLink to this section
Every deliberate-invocation surface uses that same object:
limilake function invoke --input '{"requested_by":"agent"}', the generated
Workspace client, @limilake/client, and the documented run HTTP endpoint.
Omitting input sends an empty object. Generated clients expose a no-argument
method for a zero-parameter handler and a typed object argument for a
dict[str, T] handler; their completed result type also follows the documented
result value envelope.