Skip to main content

Functions: a guide for coding agents

Synced from bicycle-studio-api

Source: studio_guide("functions") (GET /api/studio/v1/guide/functions) rendered at origin/platform (1afd83f), synced 2026-09-28. Do not edit this page here; change the source and run yarn sync:studio.

A function is a named, versioned unit of work Studio runs for any caller (an app, a workflow, an agent, MCP, chat, REST) as one invocation with one trace. It has an input_schema, an output_schema, and lists every capability it needs; nothing unlisted is reachable.

Working with the person. Agree with them what the function should answer before you write it; run function_test and function_try and show them real results before you ask them to publish; the first publish, anything that widens what it may do, and exposing it to agents or MCP are theirs to confirm in Studio (give the link and wait). Always: ask what decision the app supports before building, have them confirm sample numbers before you trust them, leave publish/approve/share/expose to them (explain, link, wait), never invent data or ids, walk them through testing, and use plain words. Full text: studio_guide(topic="protocol").

Kinds​

Kind (UI name)What it isPackage
code (Code)Python def handler(input, ctx) -> dict in a sandbox (images and limits: "The code sandbox" below)function.json, main.py, tests
llm (Ask AI)one structured model callllm: {model, prompt, effort?, max_cost_usd?} and prompts/*.md using {{input/<pointer>}}
classify (Sort into categories)one text field into a fixed label setclassify: {labels: [...], text_field, instructions?, multi_label?} (labels is a list)
agentseveral model steps and read-only tools under budgetsagent: {spec}, grants, budgets (studio_guide("agents"))

The kind cannot change after creation. What this deployment runs: function_kinds. Model ids: function_models. Ready-made Bicycle functions: function_library. effort (low | medium | high) is the only model control; there is no temperature.

The loop​

function_create(name, title) # name ^[a-z][a-z0-9_]{0,55}$
function_put_files(name, files={ # the whole package: ONE new version, validated once
"function.json": <manifest>, "main.py": <code>,
"fixtures/day.json": <json>, # one per fixture the tests name
"fixtures/model.skops": {"content": <b64>, "encoding": "base64"}}) # a binary fixture (<= 256 KiB)
function_test(name, n) # the tests, on the real executor, fixtures only
function_try(name, input) # one real run as you (llm and agent runs cost money)
function_publish(name, n) # a code-only change publishes; anything wider: a link
  • Files can be put in any order and a later put keeps the files already there, but one function_put_files call is one version; function_put_file is for a one-file edit. Give the manifest the path exactly function.json (no folder, no leading /); until it is in, a version answers "Not validated yet".
  • function.json top-level keys (anything else is refused, and the error lists these): schema, name, title, kind, entrypoint, image, input_schema, output_schema, capabilities, resources, timeout_ms, mode, deterministic, visibility, tests, llm, agent, classify, grants, budgets, evals, limits, docs. Every kind needs schema, output_schema and capabilities ([] when none). A description goes in docs: {"docs": {"summary": "<one line>", "description": "<longer>"}}.
  • A first publish, and one that widens what the function may do (a capability, model, query, audience, MCP exposure, bigger class, longer timeout, other image, higher compute budget), answers "A person must confirm this in Studio before vN ..." with the link and who may confirm. That is not an error: give the person the link and wait.
  • function_try of a function with blob.read / blob.write gets an empty throwaway blob store, or one seeded with blobs={"model-latest.json": "{...}"}. It never touches an app's or a workflow's blobs. A function with semantic.query cannot be tried alone (capability_not_granted: its caller declares the queries); its tests are the proof, then a workflow try run.
  • Other tools: function_get, function_versions, function_dependents, function_disable / function_enable (soft delete), function_settings (audience and exposure; widening needs a person), function_guide(name) (that function's "use it in an app" text).

Capabilities (capabilities[])​

idLets the codeConfig
semantic.queryrun declared semantic queriesqueries
cache.read / cache.writeread / write its own cachenames, ttl_max_s
blob.read / blob.writeread / write named blobs (a workflow's, when a workflow calls it)names
llm.callcall a model (ctx.llm(model, ..., effort=))models, max_calls, max_usd
fn.callcall other functions (depth <= 3)refs

Where a query comes from. semantic.query names query ids; the SQL is declared by the calling deployment (the app's bda.manifest.json queries, or the workflow's queries block). The function carries no SQL, so its caller must declare every id it lists (else capability_not_granted).

Visibility: visibility.audience (private | app | tenant | bicycle) and visibility.expose (apps, workflows, agents, mcp). Widening either is a person's step.

Tests​

Every code function has at least one test {name, input, fixtures?, expect}:

  • name: a slug like obvious_anomaly (^[a-z0-9][a-z0-9_-]{0,63}$).
  • fixtures: what each capability call answers, keyed <capability>:<query id | blob name | model | ref> -> a file under fixtures/. Tests never touch live data; a call with no fixture fails with "no fixture for <key>".
  • expect, one of:
expectPasses when
{"schema_only": true}the output matches output_schema
{"/orders": 120, "/rows/0/day": "2026-09-20"}each JSON pointer (1 to 64, each starting with /) holds that value
{"/wape_pct": {"$approx": 3.04, "abs": 0.05}}a number within abs (or rel) of $approx: use it for model outputs

{"orders": 120} (no leading /), {}, {"ok": true} and {"output": {...}} are refused at validation. A pointer reads the handler's return value itself: /orders, not /output/orders.

Fixture keyThe file holds
semantic.query:<query id>{"columns": [{"name": "day", "type": "string"}, {"name": "orders", "type": "number"}], "rows": [["2026-09-20", 120]], "row_count": 1, "truncated": false}
blob.read:<blob name>the blob's bytes (a JSON pointer file, or a binary model put with encoding: "base64"); no fixture means ctx.blob.get answers None
llm.call:<model>{"call_id": "t1", "model": {"requested": "<m>", "resolved": "<m>"}, "output": {"json": {...}, "text": null, "valid": true}, "usage": {}, "cost": {"usd": 0}}
fn.call:<ref>the called function's invocation result

blob.write and the cache need no fixture: each test has its own store. A fixture holding {"ok": false, "code": "capability_failed", "message": "..."} makes that call fail. A blob fixture in a test: "fixtures": {"blob.read:model-latest.json": "fixtures/latest.json"}.

function_test answers, per test, what the function returned or the exception with its traceback (up to 4 KB). A process that died says why: out of memory (with the class that fits), /tmp full, a signal, or runtime_unavailable (the runtime restarted: run the tests again).

ML functions (bda-python-ml:1)​

bda-python-ml:1 adds torch (CPU), chronos-forecasting, statsforecast and statsmodels, with amazon/chronos-2 in the image. Use "image": "bda-python-ml:1", "resources": {"class": "fn-medium"}, "mode": "async". fn-xs is refused. A cold start takes 10 to 15 s. One invocation is one forecast or one retrain; a backtest is a workflow step mapped over partitions. Save models as blobs with skops, never pickle. Working examples: example-train-predict, example-backtest.

The code sandbox (generated from the runtime and Studio)​

The runtime did not answer just now, so the image's packages, classes and timeouts are not listed here: function_kinds shows them. There is no pip install and no network in the sandbox.

Caps Studio enforces:

  • An invocation's output is at most 6 MiB; at most 200 capability calls per invocation.
  • ctx.query(...) answers at most max_rows rows (default 1,000), and never more than the declared query's maxLimit or 10,000.
  • A workflow query node answers at most 10,000 rows, and at most the declared query's maxLimit (default 1,000, up to 100,000); rows past the cap are dropped without an error, so set maxLimit and aggregate in SQL (for example by day) when history is long.

Daily compute budget: compute units are wall seconds x the class's vCPU (a call reserves its timeout_ms x vCPU and is settled to what ran). By default a function may spend 2,000 a day and a workflow's function nodes together 5,000. limits: {"compute_units_per_day": N} in function.json or in the workflow document sets its own, at most 2,000 on this deployment unless your workspace has its own maximum (more is refused in words). Raising it above what the published version had widens it: the publish review shows the change and a person confirms it in Studio; an agent cannot. A raise counts once published: a Try, a draft's run and a workflow try run get at most the default. When a budget is used up, calls answer quota_exhausted until the next UTC day. A long run is charged like any other: a function with a long timeout_ms (up to its class's maximum run time) reserves timeout x vCPU per call, so its budget must cover at least one call (validation warns when it does not).

Calling a function​

FromHow
A data appmanifest.functions + bda.fn.call(local, input) (function_guide(name) has the snippets)
A workflowa function step with ref: fn:<tenant>/<name>@<n> (needs expose.workflows)
An agentthe ref in the agent's grants.functions (needs expose.agents)
MCPfn_<name> (needs expose.mcp); a long call returns an id for invocation_get
RESTPOST /api/studio/v1/functions/{ref}:invoke (sync) or :submit (async), then GET /invocations/{id}

Worked example: a KPI code function​

{"schema": "bicycle.function/v1", "name": "order_kpis", "kind": "code", "title": "Order KPIs for a day",
"entrypoint": "main:handler", "image": "bda-python:3", "mode": "async", "timeout_ms": 10000,
"resources": {"class": "fn-xs"},
"input_schema": {"type": "object", "required": ["day"], "properties": {"day": {"type": "string"}}},
"output_schema": {"type": "object", "properties": {"orders": {"type": "number"}, "failed_pct": {"type": "number"}}},
"capabilities": [{"id": "semantic.query", "queries": ["orders_by_day"]}],
"visibility": {"audience": "tenant", "expose": {"apps": true, "workflows": true, "agents": false, "mcp": false}},
"tests": [{"name": "one-day", "input": {"day": "2026-09-20"},
"fixtures": {"semantic.query:orders_by_day": "fixtures/day.json"}, "expect": {"/orders": 120}}]}
# main.py
def handler(input, ctx):
rows = ctx.query("orders_by_day", {"from": input["day"], "to": input["day"]}).records()
orders = sum(r["orders"] for r in rows)
failed = sum(r["failed_orders"] for r in rows)
return {"orders": orders, "failed_pct": round(100 * failed / orders, 2) if orders else 0}

fixtures/day.json: {"columns": [{"name": "day", "type": "string"}, {"name": "orders", "type": "number"}, {"name": "failed_orders", "type": "number"}], "rows": [["2026-09-20", 120, 3]], "row_count": 1, "truncated": false}. The same function with an app that shows it: studio_guide("example-kpi-app").

The handler's ctx (bicycle-fn-sdk)​

The ctx a function receives: def handler(input: dict, ctx) -> dict.

ctx APIneeds the capability
ctx.query(query_id, params, max_rows)semantic.query
ctx.cache.get/set/deletecache.read / .write
ctx.blob.get/put/listblob.read / .write
ctx.llm(model, prompt=… / messages=…)llm.call
ctx.agent(ref, input)(v1.5; never granted)
ctx.call(ref, input)fn.call
ctx.log / progress / deadline_ms()always on
  • result.column_names
  • result.records() -> list[dict[str, Any]]
  • ctx.cache.get(key, default=None) -> Any
  • ctx.cache.set(key, value, ttl_s=None) -> int
  • ctx.cache.delete(key) -> bool
  • ctx.blob.list() -> list[dict[str, Any]]
  • ctx.blob.get(name) -> bytes | None
  • ctx.blob.put(name, data, content_type='application/octet-stream') -> dict
  • ctx.deadline_ms() -> int: Unix ms at which the process is killed.
  • ctx.remaining_ms() -> int
  • ctx.query(query_id, params=None, *, max_rows=None, timeout_ms=None) -> QueryResult
  • ctx.llm(model, *, prompt=None, messages=None, system=None, data=None, output_schema=None, output_format='json', max_output_tokens=None, effort=None, max_usd=None, timeout_ms=None, temperature=None) -> dict[str, Any]: One model call. effort ("low" | "medium" | "high") sets how hard the model works.
  • ctx.agent(ref, input) -> dict[str, Any]: agent.run is reserved for v1.5 (async invocations only); v1 grants never carry it.
  • ctx.call_raw(ref, input, timeout_ms=None) -> dict: The child's invocation resource, whatever its status.
  • ctx.call(ref, input, timeout_ms=None) -> dict: The child's output; raises CapabilityError if the child did not succeed.
  • ctx.log(msg, level='info') -> None
  • ctx.flush_logs() -> None
  • ctx.progress(pct, note=None) -> None

A capability the function did not list raises CapabilityError(code="capability_not_granted"); one that fails raises CapabilityError with cap and code, and if it escapes the handler the invocation fails capability_failed.

Use it in an app​

function_guide(name) answers one function's text: the manifest import, the bda.fn calls, its input and output, cost and time. The bda.fn rules: studio_guide("data-apps").

guide_version bb2461328de4