Docs
Contents

Functions

Overview and use cases

Server-side serverless functions respond to HTTP / SDK calls, platform events, and scheduled tasks, running in an isolated sandbox (the managed environment runs on ACS Agent Sandbox; local Docker is based on OpenRuntimes). Suitable for backend logic proxies, event-driven processing, scheduled tasks, and lightweight APIs; for complex authorization scenarios, first read Permissions Explanation.

Prerequisites

Usage workflow

  1. Check capabilities: before creating or modifying, query functions.listRuntimes() and functions.listSpecifications() separately. Select runtime from the runtime list and runtimeSpecification from enabled specifications. SDK enums are candidates; availability also depends on instance configuration and plan limits.

  2. Create the function: call functions.create, specifying the identifier, name, runtime, and permissions; configuration options are in the parameter table below. The following is a schematic of the parameter structure, where ? marks optional items; for complete calls, see Examples by language.

    functions.create({
      functionId, name, runtime,
      execute?, events?, schedule?, timeout?, enabled?, logging?,
      entrypoint?, commands?, scopes?, runtimeSpecification?,
      runtimeReplicas?, runtimeKeepAliveMode?, ...
    })
  3. Deploy: upload the source archive and create a Deployment.

    functions.createDeployment({
      functionId,
      code: InputFile.fromPath('code.tar.gz', 'code.tar.gz'),
      activate: true,
      entrypoint,
      commands,
    });

    The status transitions through waiting → processing → building → ready, with failed / canceled as failure paths. After cancellation or a long wait, you should re-read the Deployment and judge based on the build logs — do not rely on a single API response.

  4. Invoke:

    • Client / Server SDK: functions.createExecution({ functionId, body, async, xpath, method, headers, scheduledAt }) (xpath, method, headers, scheduledAt are all optional).

    • Synchronous (async: false) waits for the execution result, with limits dependent on the function and deployment configuration; asynchronous execution returns an execution ID that can be polled with getExecution; scheduledAt supports future schedules (ISO 8601, minute precision).

    • HTTP direct access to the function URL (requires the execute permission to include the corresponding origin).

  5. Call Agentbase from within the function: use a dynamic API Key (req.headers['x-appwrite-key'], permissions = the function's scopes parameter, from the administrator's perspective) or the caller's JWT (x-appwrite-user-jwt, subject to row-level permissions); for Client, use the runtime-injected APPWRITE_FUNCTION_API_ENDPOINT endpoint (do not assemble an external domain yourself — DNS cannot resolve it inside the self-hosted sandbox).

  6. Events and schedules: subscribe to platform events with the events array (e.g., tablesdb.*.tables.*.rows.*.create, users.*.create); fill schedule with a Cron expression.

  7. Variables: createVariable / listVariables / updateVariable / deleteVariable (secret: true is stored encrypted and read at runtime via process.env).

  8. Switch active deployment: updateFunctionDeployment({ functionId, deploymentId }) switch the active deployment.

Key parameters and returns

Multi-language / multi-runtime / multi-replica

ConfigurationValuesDescription
runtimee.g. node-22, python-3.9, go-1.23 (subject to listRuntimes())Corresponds to the SDK Runtime enum
runtimeSpecificatione.g. s-0.5vcpu-1gb, s-1vcpu-2gb, s-2vcpu-4gb, s-4vcpu-8gb, s-8vcpu-16gbPass the slug string directly; it must appear in listSpecifications()'s enabled list; the Node SDK has no such enum
runtimeReplicas1 / 2 / 3 / 5 / 10, default 1Can reuse the runtime replica desired value
runtimeKeepAliveModedisabled / always / schedulewarm strategy; schedule requires runtimeKeepAliveStart/End (HH:mm) + IANA runtimeKeepAliveTimezone

The warm configuration is a Function-level desired value and does not equal the environment's shared warm pool inventory; shared pool verification (warmPoolReplicas, inventory ready/available, createOnNoStock) belongs to operations, and the SDK provides no query for it.

Two independent permission sets

ConfigurationWhat it controlsTypical values
executewho may trigger (Client SDK / HTTP)['users'], ['any'], ['team:xxx']
scopesResources the function runtime's dynamic API Key can accessMinimize based on actual in-function calls, e.g. databases.read/write, tables.read/write, rows.read/write, users.read

This is distinct from "the API Key scopes used by the deployment script"; do not substitute one for the other.

Execution returns

$id, functionId, deploymentId, trigger (http/schedule/event), status (waiting/processing/completed/failed/scheduled), responseStatusCode, responseBody, duration, logs/errors (visible only with an API Key; usually empty via the Client SDK).

Errors and boundaries

SDK Category Differences

Java 17 prebuilt JAR (Node.js Server)

The management script pins the exact version agentbase-node-sdk@2.12.0. The target Function must already have selected java-17.0; the JAR's manifest declares Main-Class and the package contains that class, the app listens on port 3000 and provides /__opr/health. The deploy Key requires functions.write, and lookup additionally requires functions.read; actually triggering execution further requires execution.write.

import { Client, Functions, ArtifactMode } from 'agentbase-node-sdk';
import { InputFile } from 'agentbase-node-sdk/file';

const client = new Client()
    .setEndpoint(process.env.APPBASE_ENDPOINT) // Includes /v1
    .setProject(process.env.APPBASE_PROJECT_ID)
    .setKey(process.env.APPBASE_API_KEY);
const functions = new Functions(client);

const deployment = await functions.createDeployment({
    functionId: process.env.APPBASE_FUNCTION_ID,
    code: InputFile.fromPath('./app.jar', 'app.jar'),
    artifactMode: ArtifactMode.Javajar,
    activate: false,
});
console.log(deployment.$id, deployment.status);

ArtifactMode.Javajar corresponds to java-jar. In this mode you do not fill in source entrypoint or build commands; the JAR's real entry point comes from the manifest, and Index.java in the response is a compatibility identifier. The default JAR cap is 100,000,000 bytes, also subject to the plan's deployment cap. The SDK handles chunked upload; do not treat an upload progress of 100% as successful deployment creation.

The example uses activate: false so the artifact can be inspected first. After receiving the deployment ID, use getDeployment({ functionId, deploymentId }) for bounded polling and check the logs; once ready is reached, call updateFunctionDeployment according to the business release schedule. Use get({ functionId }) to look up the Function's deploymentId, confirm it matches the target deployment, then run one business request and check the actual response. If failed / canceled or the wait times out, stop the release and troubleshoot; a deployment being ready does not mean it is activated, nor does it guarantee business request success.

Filtering execution records (Node.js Server)

Reading execution records requires execution.read. The HTTP parameter name is path; in Node Server 2.10.0 the object parameter name is xpath; pathMatch defaults to exact matching. The following combines a path regex with the GET method, limiting one page to at most 20 records:

import { Client, Functions, Method, PathMatch, Query } from 'agentbase-node-sdk';

const client = new Client()
    .setEndpoint(process.env.APPBASE_ENDPOINT)
    .setProject(process.env.APPBASE_PROJECT_ID)
    .setKey(process.env.APPBASE_API_KEY);
{
  const prepareRequest = client.prepareRequest.bind(client);
  client.prepareRequest = (...args) => {
    const request = prepareRequest(...args);
    request.options.redirect = 'error';
    return request;
  };
}
const functions = new Functions(client);

const page = await functions.listExecutions({
    functionId: process.env.APPBASE_FUNCTION_ID,
    xpath: '^/articles/[0-9]+$',
    pathMatch: PathMatch.Regex,
    method: Method.GET,
    queries: [Query.limit(20)],
});
console.log(page.executions.map(({ $id, status }) => ({ $id, status })));

The path includes the query string; the expression above will not match /articles/42?draft=1 — use ^/articles/[0-9]+([?].*)?$ instead if the query string should be included. The regex carries no /…/ delimiters. Use Query.cursorAfter to continue paginating as needed, and clear the original cursor when changing filter conditions; do not treat the current page's or total: false's zero count as the full result set.

listExecutionPaths returns matching full paths, and listExecutionsByPath returns the execution records for that condition; both also support these filter conditions. Do not rewrite a waiting or processing execution as failed on the client merely because the timeout has passed, and do not delete it; the actual terminal state is determined by the server's record.

Examples by language

The following provides examples by language, item by item along the usage workflow; each card can switch languages (synced across the page).

Query capabilities and create functions

The Go examples return errors to the caller. First initialize cl as described in Go SDK initialization, then pass the service created by agentbase.NewFunctions(cl) to subsequent examples. Handle returned errors according to the application.

The Node.js, Java, Python, and Go examples query specifications; running the complete query-and-create flow requires an API key with functions.read and functions.write. Grant only the relevant scope when performing a single operation.

import { Client, Functions, Runtime, Scopes } from 'agentbase-node-sdk';

const client = new Client()
    .setEndpoint(process.env.APPBASE_ENDPOINT!)   // Must include /v1
    .setProject(process.env.APPBASE_PROJECT_ID!)
    .setKey(process.env.APPBASE_API_KEY!);        // functions.read for specifications, functions.write for creation
{
  const prepareRequest = client.prepareRequest.bind(client);
  client.prepareRequest = (...args) => {
    const request = prepareRequest(...args);
    request.options.redirect = 'error';
    return request;
  };
}
const functions = new Functions(client);

const runtimes = await functions.listRuntimes();          // The runtimes actually available on the instance
const specs = await functions.listSpecifications();       // Build/run specs actually available on the instance
// Choose a runtime and an enabled specification separately; SDK enums are only candidates
const fn = await functions.create({
    functionId: 'send-mailer',
    name: '发送邮件',
    runtime: Runtime.Node22,            // Refer to the actual return of listRuntimes()
    execute: ['users'],            // Who can trigger it; no roles granted by default
    entrypoint: 'src/main.ts',
    commands: 'npm install',
    scopes: [Scopes.UsersRead],        // Permissions of dynamically used API keys inside functions should be minimized as needed
});

Deploy the code package

createDeployment uploads the .tar.gz code package (multipart/form-data); the build runs asynchronously (waiting → processing → building → ready) and a deployment record in building state is returned immediately. Code package upload is provided only on the Node and REST surfaces; Java / Python / Go omit this tab.

import { Functions } from 'agentbase-node-sdk';
import { InputFile } from 'agentbase-node-sdk/file';

const dep = await functions.createDeployment({
    functionId: 'send-mailer',
    code: InputFile.fromPath('code.tar.gz', 'code.tar.gz'),
    activate: true,
    entrypoint: 'src/main.ts',
    commands: 'npm install',
});
// After cancellation or a long wait, re-read the deployment record and combine it with build logs; do not trust a single API response alone

Trigger execution and poll

Synchronous (async: false) waits for the execution result, subject to function and environment limits; asynchronous execution returns an execution ID that can be polled with getExecution; scheduledAt supports future scheduling (ISO 8601, minute precision); you can also trigger via the function URL over direct HTTP (requires the execute permission to include the corresponding origin).

Synchronous and asynchronous calls are alternatives; each creation call starts a new execution. The asynchronous examples below start one execution and query its state once; a successful query does not mean the business operation is complete. If a final state is required, poll at intervals with a deadline; if the deadline expires before completion, check state and side effects before any retry.

import { ExecutionMethod } from 'agentbase-node-sdk';

const execution = await functions.createExecution({
    functionId: 'send-mailer',
    body: JSON.stringify({ to: 'a@b.c' }),
    async: true,
    xpath: '/',
    method: ExecutionMethod.POST,
    headers: { 'X-Custom-Header': 'value' },
});
const current = await functions.getExecution({ functionId: 'send-mailer', executionId: execution.$id });

Execution path query (2.9.0)

Look up execution records by request path: listExecutionPaths lists the deduplicated request paths that have produced execution records (string ascending, paginated); listExecutionsByPath paginates the executions under a path by request path (the HTTP parameter path is required, ≤2048 characters; the Node.js object parameter is xpath). Both require execution.read. From 2.10.0 the two methods gain filters: HTTP path (Node.js xpath, with listExecutionPaths optional), pathMatch (exact / regex, default exact), and method (exact HTTP method filter).

const paths = await functions.listExecutionPaths({ functionId: 'send-mailer' });   // { paths, total }
const onPath = await functions.listExecutionsByPath({
    functionId: 'send-mailer',
    xpath: '/webhook',          // Exact match on the full path
});                            // { executions, total }

Calling Agentbase again from within a function

This is the in-function capability surface, not a management API call — this card only covers the Node (function runtime) tab; other language runtimes and REST have no corresponding tab. The Client's endpoint uses the runtime-injected APPWRITE_FUNCTION_API_ENDPOINT (external domains cannot be resolved inside the self-hosted sandbox); choose one of two credentials: the dynamic API Key (permissions = the function's scopes parameter, admin perspective) or the caller's JWT (subject to row-level permissions).

// Inside the function code (Node runtime)
import { Client } from 'agentbase-node-sdk';

export default async ({ req, res }) => {
    // Method One: dynamic API key (permissions = the function's scopes parameter)
    const admin = new Client()
        .setEndpoint(process.env.APPWRITE_FUNCTION_API_ENDPOINT!)   // Injected at runtime, always takes priority
        .setProject(process.env.APPWRITE_FUNCTION_PROJECT_ID!)
        .setKey(req.headers['x-appwrite-key']!);
    {
      const prepareRequest = admin.prepareRequest.bind(admin);
      admin.prepareRequest = (...args) => {
        const request = prepareRequest(...args);
        request.options.redirect = 'error';
        return request;
      };
    }

    // Method Two: caller's JWT (present when triggered by the SDK; constrained by row-level permissions)
    const jwt = req.headers['x-appwrite-user-jwt'];
    if (jwt) {
        const asUser = new Client()
            .setEndpoint(process.env.APPWRITE_FUNCTION_API_ENDPOINT!)
            .setProject(process.env.APPWRITE_FUNCTION_PROJECT_ID!)
            .setJWT(jwt);
        {
          const prepareRequest = asUser.prepareRequest.bind(asUser);
          asUser.prepareRequest = (...args) => {
            const request = prepareRequest(...args);
            request.options.redirect = 'error';
            return request;
          };
        }
    }
    return res.json({ ok: true });
};

Events and schedules

events subscribes to platform events (e.g. users.*.create, tablesdb.*.tables.*.rows.*.create); schedule takes a CRON expression; both can also be passed in when creating the function.

Before updating a function, read its current configuration and submit the settings that must be retained according to the update API. Some omitted fields take API defaults; do not assume all omitted fields remain unchanged. The function name is required. Before updating schedule to a non-empty value, ensure exactly one compact execution schedule exists. If none exists, consider managing a separate schedule through the schedules API; a newly created independent rule is not a compact rule. If multiple rules exist, inspect them before resolving the conflict.

Environment variables

Build and runtime inject the function process via environment variables (read inside the function through process.env); secret: true secret variables can be updated/deleted but their plaintext cannot be read back; changes take effect for subsequent executions only after redeploying (or reactivating a deployment).

const variable = await functions.createVariable({
    functionId: 'send-mailer',
    key: 'DATABASE_URL',
    value: 'postgres://...',
    secret: true,            // true = encrypted storage, cannot be read back
});
const vars = await functions.listVariables({ functionId: 'send-mailer' });
await functions.updateVariable({
    functionId: 'send-mailer',
    variableId: variable.$id,
    key: 'DATABASE_URL',
    value: 'postgres://new',
});
await functions.deleteVariable({ functionId: 'send-mailer', variableId: variable.$id });

Switch the active deployment

updateFunctionDeployment switches the activation deployment pointer to an existing deployment; from then on, all access and execution of that function uses the newly activated deployment's code.

await functions.updateFunctionDeployment({
    functionId: 'send-mailer',
    deploymentId: '<deploymentId>',
});

Example Guide

2.12.0 — Multiple recurring tasks

Use Projects in SDK 2.12.0 with schedules.read / schedules.write on the project key. Each task invokes the current active deployment of the same function. Legacy Functions.schedule only projects the compact task, not all schedules. The type is immutable; multiple interval / cron / quartz tasks are supported. active defaults to false. Request data is a JSON object string; response data is already an object. Lists default to 25 and allow at most 100; use the last ID as a cursor when hasMore is true. Request path input uses data.inputType=requestpath and data.requestPath to invoke GET against the current function. Omission uses POST JSON input.

Disabling or deleting cannot cancel admitted execution. Runtime keepalive is an independent system task outside normal schedule CRUD. Deploy to ready before enabling and check execution records after changes; a next time is not execution success.

import { Client, Projects, Query, ResourceType, ScheduleType } from 'agentbase-node-sdk';
const projectId = process.env.AGENTBASE_PROJECT_ID;
const client = new Client().setEndpoint(process.env.AGENTBASE_ENDPOINT)
  .setProject(projectId).setKey(process.env.AGENTBASE_API_KEY);
{
  const prepareRequest = client.prepareRequest.bind(client);
  client.prepareRequest = (...args) => {
    const request = prepareRequest(...args);
    request.options.redirect = 'error';
    return request;
  };
}
const projects = new Projects(client);
const task = await projects.createSchedule({ projectId,
  resourceType: ResourceType.Functions, resourceId: process.env.AGENTBASE_FUNCTION_ID,
  scheduleType: ScheduleType.Quartz,
  schedule: JSON.stringify({ expression: '0 0 9 * * ?', timezone: 'Asia/Shanghai' }),
  data: JSON.stringify({ body: JSON.stringify({ task: 'daily-report' }) }), active: false });
const saved = await projects.getSchedule({ projectId, scheduleId: task.$id });
const page = await projects.listSchedules({ projectId,
  queries: [Query.equal('resourceId', process.env.AGENTBASE_FUNCTION_ID), Query.limit(25)], total: false });
console.log(saved.active, page.hasMore);
await projects.updateSchedule({ projectId, scheduleId: task.$id, active: false });
await projects.deleteSchedule({ projectId, scheduleId: task.$id });