Skip to main content

Agent functions

An agent function is a short piece of JavaScript that your AI agent runs when it needs custom logic: looking up a record, calling one of your systems, or preparing data before the agent replies. From its code, an agent function can work with your tables, call the APIs configured for your agent, read and update global variables, and, on runtime 2026.10.19, send messages to the user while it works.

Where agent functions run​

WhereHow it's calledTypical use
Agent toolThe agent decides to call it during a conversation and fills in the inputs. See Function tool."Where is my order?", "Book an appointment"
Function nodeA flow reaches the node and passes in the values you mapped.Validating input, saving a lead, formatting data
Lifecycle hook or tool hookThe agent runs it at a set moment, for example On session start or Before tool call, and can save what it returns with Save result to.Loading the customer's details before the first reply
Run buttonYou run it from the editor with test values.Testing while you build

What happens to what the function sends and returns depends on where it runs:

Agent tool or hookFunction node
InputsFilled in by the agent (or the hook) and checked against the declared inputsMapped on the node. Text values are converted to the declared types first. A mapped input the function no longer declares is ignored.
Return valueRead by the agent as the tool's result. Save result to stores it in a variable.Stored in the node's output variable
Messages it yieldsSent to the user as they're yieldedNot sent
haltTurn, endCall, transferCallCarried out after the function returnsNot carried out. The action itself becomes the node's output.
When the function failsThe agent is told the error and decides what to say. See Errors.The output variable gets the error message, or is left empty, and the flow carries on to the next node. There's no separate error path.

Before you start​

Agent functions are available on v3 AI agents that have agent functions turned on. If Build → Functions → Add creates a function straight away without offering Agent functions, the option isn't enabled for your agent yet. Functions you've already created stay listed either way.

The other choice there, Classic functions, is the earlier kind: only a Function node in a flow can run it, and agents can't call it as a tool.

Create an agent function​

  1. Go to Build → Functions and click Add.
  2. Choose Agent functions and give the function a name.
  3. Write a Description, up to 500 characters. Agents read it to decide when to call the function, so a function without one isn't offered to agents, and you can't save without one.
  4. Under Inputs, click Add input for each value the function needs. Give each one a name, a type, a description, and whether it's required. See Inputs.
  5. Write the code. A new function starts on the newest runtime version, with that version's starter code. Then click Run to test it with sample inputs. See Testing and logs.
  6. Save. Then add it to an agent from the agent's tools, or add a Function node to a flow.

Function names are 2 to 50 characters, start with a lowercase letter, and use only letters and numbers (camelCase), for example getOrderStatus. main is reserved. The code can be up to 85,000 characters.

Only the inputs you declare reach the function. A call with an input that isn't declared, without a required one, or with a value of the wrong type is refused before your code runs, and the agent is told why.

Structure of an agent function​

Every function is a JavaScript module whose default export is the function. It receives two arguments, inputs and context, and what it returns is its result.

On runtime 2026.10.19, the version every new function starts on, the default export is an async generator, written async function*:

import { tables, apis, variables, crypto } from "@yellow/bot";

export default async function* (inputs, context) {
// your logic
return { /* result */ };
}

A function that never uses yield works like an ordinary function. On runtime 2026.08.29, functions created before runtime versions existed, the export is a plain async function (inputs, context) instead. Match the version shown in the editor's status bar: on 2026.10.19 a plain async function is refused with "the default export must be an async generator", and on 2026.08.29 nothing a function yields reaches the user, because the messages module doesn't exist there. See Runtime versions.

Import only what you use. These are the modules a function can import:

ModuleWhat it gives youRuntime
@yellow/bottables, apis, variables and cryptoevery version
@yellow/bot/responsesSend messages while the function runs: sendMessage, sendQuickReplies, sendCards, sendImage, sendVideo, sendFile2026.10.19
@yellow/bot/voiceWork with voice calls: endCall, transferCall2026.10.19
@yellow/bot/agentHalt the agent's turn: haltTurn2026.10.19

Any other import, such as "node:fs", "axios" or a relative path, is refused. console, Buffer, URL, URLSearchParams and Intl need no import. See JavaScript in functions.

import { tables } from "@yellow/bot";
import { sendMessage } from "@yellow/bot/responses";

export default async function* ({ orderId }, context) {
yield sendMessage("One moment while I check that order…"); // reaches the user now
const [order] = await tables.search("orders", { "orders.order_id": orderId }, { limit: 1 });
return order ? { found: true, status: order.status } : { found: false };
}

Inputs​

inputs holds the values for this call: filled in by the agent, mapped by a flow node, or typed in when you click Run. It's always an object, so const { email } = inputs is safe even when nothing was passed. An optional input that wasn't passed is undefined.

Input typeArrives asExample value
stringText"A-1001"
numberA number, whole or decimal2, 149.5
booleantrue or falsetrue
objectAn object{ "city": "Pune", "pin": "411001" }
arrayA list["red", "blue"]

Input names start with a letter and use only letters, numbers and _, because the code reads them as inputs.<name>. There's no default value: give the default in code, as in const { limit = 5 } = inputs.

For more detail, such as allowed values or the fields of an object, click Edit as JSON on the Inputs tab and describe the input with JSON Schema: properties, items, required, enum and anyOf. The agent sees this schema, and calls are checked against it.

{
"type": "object",
"properties": {
"orderId": { "type": "string", "description": "The order number, for example A-1001" },
"reason": { "type": "string", "enum": ["damaged", "late", "changed_mind"] },
"items": {
"type": "array",
"items": { "type": "object", "properties": { "sku": { "type": "string" }, "qty": { "type": "number" } } }
}
},
"required": ["orderId", "reason"]
}
export default async function* ({ orderId, reason, items = [], note }) {
const units = items.reduce((sum, item) => sum + (item.qty ?? 1), 0);
return { orderId, reason, units, hasNote: note !== undefined };
}

A call is refused before your code runs when an input is missing, isn't declared, or has the wrong type. The agent reads, for example, Function 'cancelOrder' was called with invalid inputs: missing required input 'orderId' and usually asks the user for the value. In a Function node the node fails the same way.

context​

Read-only information about the current call. Every text field is present, and "" when there's nothing to report. Assigning to context throws.

FieldDescription
botIdThe agent running the function, whose tables and APIs it reaches
senderThe user's ID on this channel
sessionIdThe current conversation session
messageIdThe incoming message this run belongs to
traceIdAn ID to pass to your own APIs so their logs can be matched with ours
sourceThe channel, for example "whatsapp" or "yellowmessenger" (web)
pageUrlThe page the web widget is on. "" on other channels.
userMessageThe user's latest message, translated and masked the way the agent sees it
profile, userThe user's profile and user properties. {} when there are none.
callSidThe voice call ID. "" when the conversation isn't a call, so it tells a call from a chat.
invokedBy"agent" (a tool or hook), "flow" (a Function node) or "dev-run" (the Run button)
agentSlug, journeySlug, nodeIdThe agent, flow or Function node that made the call. Left out, not "", when there isn't one.

When you test with Run, there's no conversation, so sessionId, messageId and userMessage are empty and source is "studio-dev-run".

sender and profile say who the platform believes it is talking to. Don't treat them as proof of identity, for example before showing account details.

export default async function* (inputs, context) {
const onCall = context.callSid !== "";
const name = context.profile.name ?? "there";
console.info("Called by", { invokedBy: context.invokedBy, agent: context.agentSlug ?? null });
return { greeting: onCall ? `Hello ${name}, thanks for calling.` : `Hi ${name}!` };
}

context isn't an import: import { context } from "@yellow/bot" fails with "Could not find export 'context'".

Return value​

What you return goes back to the agent, or becomes the output of the Function node. Return plain data: objects, arrays, text, numbers, true/false and null. The result is converted to JSON, so:

  • undefined, and a function, become null. A property whose value is undefined is dropped.
  • A Date becomes its ISO text, for example "2026-10-29T10:00:00.000Z".
  • A BigInt, or an object that refers to itself, can't be converted, and the function fails.
  • The result can be up to 10 MB, but keep it small: the agent reads all of it.

On runtime 2026.10.19 you can also return an action instead of plain data: haltTurn(result), endCall() or transferCall(options).

Tables, columns and APIs in code​

You don't type table, column or API names. The editor suggests them, and the one you pick appears in your code as a chip: a table as orders, a column as orders.email (table, then column), and an API as getOrderStatus.

const [order] = await tables.search("orders", {
"orders.email": email,
});
const res = await apis.execute("getOrderStatus", { orderId: order.order_id });

What the editor stores​

A chip is only how the editor displays a reference. The text saved in your code is a $bot_ reference that holds an ID, not the name:

You pickThe editor showsSaved in your code
A tableorders$bot_table_<tableId>, for example $bot_table_671209d9a0ac67166082478f
A columnorders.email$bot_table_column_<tableId>_<slot>, for example $bot_table_column_671209d9a0ac67166082478f_s3. The slot (s1, s2, …) is where the table stores the column.
An APIgetOrderStatus$bot_api_<apiName>, for example $bot_api_getOrderStatus

So the search above is saved as:

const [order] = await tables.search("$bot_table_671209d9a0ac67166082478f", {
"$bot_table_column_671209d9a0ac67166082478f_s3": email,
});
const res = await apis.execute("$bot_api_getOrderStatus", { orderId: order.order_id });

The function sends these references as they are, and the platform looks up the table, column and API from them. That's why:

  • Renaming a table or column doesn't break your code: the ID stays the same. An API can't be renamed.
  • A plain name doesn't work. tables.search("orders", …) with orders typed as text, a column typed as "email" or "s3", or an API typed as "getOrderStatus" stops the function with "must be a Studio reference". Copying or pasting the whole chip keeps the reference.
  • A column must belong to the table you're searching or updating. A column from another table stops the function with column '…' belongs to table '…', not '…'.
  • Code copied from another agent keeps the other agent's IDs. They don't match your tables, so the editor shows the chip as ⚠ unknown table, ⚠ unknown column or ⚠ unknown API. Delete it and pick your own from the suggestions.
  • The system columns id, created_at and updated_at have no chip. Write them by name, and only in sort and columns.
  • Rows that come back from a search are keyed by column name, so you read row.email, not the chip.

Get suggestions​

Typing a quote after tables.search( lists the tables (customers, leads, orders, support_tickets); typing ord narrows it to orders. Typing @email inside a string lists the email column of each table and orders.email is picked. Typing a quote after apis.execute( lists the APIs, and getOrderStatus is picked. The finished code shows orders, orders.email and getOrderStatus as chips.

Type " after tables.search( for tables, "@ for columns, and " after apis.execute( for APIs.
Where you're typingWhat to typeWhat you get
The first argument of tables.search(, tables.insert( or tables.update("Your tables
The first argument of apis.execute("Your APIs
After column: or inside columns: ["Your columns
Anywhere else, for example a filter key, the fields of a row you insert, or set in an update@, or "@ inside a stringEvery table, column and API

Keep typing to narrow the list by name, for example @ord shows orders and its columns. Press Enter to insert the highlighted one; the @ is replaced by the chip.

await tables.search("orders", { // typed " after search( and picked orders
"orders.email": email, // typed "@email and picked orders.email
});

Columns that aren't searchable are marked column · not filterable in the list. You can read and write them, but avoid using them in a filter.

Things to know​

  • In the examples on these pages, a chip such as orders, orders.email or getOrderStatus is a reference you insert from the suggestions. Copying an example's text doesn't insert the references; pick each one from the suggestions in your own editor, using your own table, column and API names.

What isn't available​

Agent functions don't run in Node.js or a browser. fetch, setTimeout, setInterval, require, process, eval, atob and btoa don't exist, and npm packages can't be imported. Use apis.execute for HTTP calls and Buffer.from(value, "base64") for base64. URL, URLSearchParams, Intl and Buffer are available. The full list is in JavaScript in functions.

Each run starts fresh: nothing in memory carries over to the next call. Keep anything you need later in a table or a global variable.

Saving checks your code, and the Problems tab lists what to fix. For example, every if, for and while needs braces, so write if (!order) { return { found: false }; }, not if (!order) return { found: false };. Errors block saving, and Run stays off until both errors and warnings are fixed.

Limits​

These limits apply each time a function runs.

Calls​

ActionLimit per runDetails
Database searches5Up to 100 rows each (10 by default), so at most 500 rows per run
Database inserts5One row each
Database updates5Each may change at most 5 rows
API calls5
Calls running at the same time2Database and API calls together. A third call started while two are still running is refused.
Messages sent with yield10Each up to 256 KB. See Send messages.
Log lines30Label up to 100 characters; value shortened after 300

A call past one of these limits stops the function with an error that names the limit. The one exception is the number of rows: a search that asks for more than 100 rows returns 100, without an error. See paging.

Time and size​

ResourceLimit per run
Total run time60 seconds, including the time spent waiting for database and API calls
Computing time2 seconds of your own code running
Code between two awaits0.5 seconds
Memory32 MB
Inputs4 MB
Return value10 MB
A Buffer1 MB
Code85,000 characters

A function that goes past one of these is stopped, and the error says which limit it hit, for example interrupted: wall/CPU budget exceeded … or out of memory: heap limit exceeded …. See Errors.

Write efficient functions​

  • Ask only for what you use. Pass columns to a search so each row carries only the columns you read, and keep limit as low as the job needs.
  • Filter in the database, not in your code. A filter in tables.search returns only the rows you want; fetching every row and filtering them in a loop uses up your 5 searches.
  • Return only what the caller needs. A small result is faster for the agent to read.
  • Run independent calls in pairs with Promise.all, never more than two at a time.
  • Keep heavy loops short. Code that computes without an await for half a second is stopped.
  • Don't hold large responses. A big API or search response counts against the 32 MB of memory; ask for less instead.

In this section​