# 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](work-with-tables.md), [call the APIs](call-apis.md) configured for your agent, [read and update global variables](use-global-variables.md), and, on runtime 2026.10.19, [send messages](send-messages.md) to the user while it works.

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](work-with-tables.md), [call the APIs](call-apis.md) configured for your agent, [read and update global variables](use-global-variables.md), and, on runtime 2026.10.19, [send messages](send-messages.md) to the user while it works.

## Where agent functions run

| Where | How it's called | Typical use |
|---|---|---|
| **Agent tool** | The agent decides to call it during a conversation and fills in the inputs. See [Function tool](../../tools/functions.md). | "Where is my order?", "Book an appointment" |
| **Function node** | A flow reaches the node and passes in the values you mapped. | Validating input, saving a lead, formatting data |
| **Lifecycle hook** or **tool hook** | The 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** button | You 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 hook | Function node |
|---|---|---|
| Inputs | Filled in by the agent (or the hook) and checked against the declared inputs | Mapped on the node. Text values are converted to the declared types first. A mapped input the function no longer declares is ignored. |
| Return value | Read by the agent as the tool's result. **Save result to** stores it in a variable. | Stored in the node's output variable |
| [Messages](send-messages.md) it yields | Sent to the user as they're yielded | Not sent |
| [`haltTurn`](halt-the-agents-turn.md), [`endCall`, `transferCall`](end-or-transfer-a-call.md) | Carried out after the function returns | Not carried out. The action itself becomes the node's output. |
| When the function fails | The agent is told the error and decides what to say. See [Errors](handle-errors.md). | 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](#inputs).
5. Write the code. A new function starts on the newest [runtime version](runtime-versions.md), with that version's starter code. Then click **Run** to test it with sample inputs. See [Testing and logs](test-and-debug.md).
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*`:

```js

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](runtime-versions.md).

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

| Module | What it gives you | Runtime |
|---|---|---|
| `@yellow/bot` | [`tables`](work-with-tables.md), [`apis`](call-apis.md), [`variables`](use-global-variables.md) and [`crypto`](crypto-helpers.md) | every version |
| `@yellow/bot/responses` | [Send messages](send-messages.md) while the function runs: `sendMessage`, `sendQuickReplies`, `sendCards`, `sendImage`, `sendVideo`, `sendFile` | 2026.10.19 |
| `@yellow/bot/voice` | [Work with voice calls](end-or-transfer-a-call.md): `endCall`, `transferCall` | 2026.10.19 |
| `@yellow/bot/agent` | [Halt the agent's turn](halt-the-agents-turn.md): `haltTurn` | 2026.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](javascript-in-functions.md).

```js

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 type | Arrives as | Example value |
|---|---|---|
| `string` | Text | `"A-1001"` |
| `number` | A number, whole or decimal | `2`, `149.5` |
| `boolean` | `true` or `false` | `true` |
| `object` | An object | `{ "city": "Pune", "pin": "411001" }` |
| `array` | A 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.

```json
{
  "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"]
}
```

```js
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.

| Field | Description |
|---|---|
| `botId` | The agent running the function, whose tables and APIs it reaches |
| `sender` | The user's ID on this channel |
| `sessionId` | The current conversation session |
| `messageId` | The incoming message this run belongs to |
| `traceId` | An ID to pass to your own APIs so their logs can be matched with ours |
| `source` | The channel, for example `"whatsapp"` or `"yellowmessenger"` (web) |
| `pageUrl` | The page the web widget is on. `""` on other channels. |
| `userMessage` | The user's latest message, translated and masked the way the agent sees it |
| `profile`, `user` | The user's profile and user properties. `{}` when there are none. |
| `callSid` | The 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`, `nodeId` | The 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.

```js
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)`](halt-the-agents-turn.md), [`endCall()` or `transferCall(options)`](end-or-transfer-a-call.md).

## 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.

```js
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 pick | The editor shows | Saved in your code |
|---|---|---|
| A table | orders | `$bot_table_<tableId>`, for example `$bot_table_671209d9a0ac67166082478f` |
| A column | orders.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 API | getOrderStatus | `$bot_api_<apiName>`, for example `$bot_api_getOrderStatus` |

So the search above is saved as:

```js
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

<figure className="yd-demo">

![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.](https://cdn.yellowmessenger.com/assets/yellow-docs/img/v3-functions-suggestions.gif)

<figcaption>Type <code>"</code> after <code>tables.search(</code> for tables, <code>"@</code> for columns, and <code>"</code> after <code>apis.execute(</code> for APIs.</figcaption>
</figure>

| Where you're typing | What to type | What 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 string | Every 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.

```js
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`](call-apis.md) 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](javascript-in-functions.md).

Each run starts fresh: nothing in memory carries over to the next call. Keep anything you need later in a [table](work-with-tables.md) or a [global variable](use-global-variables.md).

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

| Action | Limit per run | Details |
|---|---|---|
| Database searches | 5 | Up to 100 rows each (10 by default), so at most 500 rows per run |
| Database inserts | 5 | One row each |
| Database updates | 5 | Each may change at most 5 rows |
| API calls | 5 | |
| Calls running at the same time | 2 | Database and API calls together. A third call started while two are still running is refused. |
| Messages sent with `yield` | 10 | Each up to 256 KB. See [Send messages](send-messages.md#limits). |
| Log lines | 30 | Label 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](work-with-tables.md#page-through-many-rows).

### Time and size

| Resource | Limit per run |
|---|---|
| Total run time | 60 seconds, including the time spent waiting for database and API calls |
| Computing time | 2 seconds of your own code running |
| Code between two `await`s | 0.5 seconds |
| Memory | 32 MB |
| Inputs | 4 MB |
| Return value | 10 MB |
| A `Buffer` | 1 MB |
| Code | 85,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](handle-errors.md#errors-you-may-see).

### 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

- [Runtime versions](runtime-versions.md): which version a function runs on, what each one adds, and how to upgrade
- [Send messages](send-messages.md): talk to the user while the function runs, with text, buttons, cards, images, videos and files
- [Work with voice calls](end-or-transfer-a-call.md): hang up or transfer a voice call from code
- [Halt the agent's turn](halt-the-agents-turn.md): stop the agent repeating what the function already said
- [Work with tables](work-with-tables.md): search, insert and update rows from an agent function
- [Call APIs](call-apis.md): call your configured APIs from an agent function and handle errors
- [Use global variables](use-global-variables.md): read and update shared values
- [Crypto helpers](crypto-helpers.md): IDs, hashing, signing and encryption
- [JavaScript in functions](javascript-in-functions.md): the language version, `Buffer`, `URL`, `Intl`, dates, and what's blocked
- [Handle errors](handle-errors.md): how failures reach the agent or flow, the errors you may see, and patterns that keep the conversation going
- [Test and debug](test-and-debug.md): the **Run** button, tests, `console`, and logs in Analysis
- [Examples](examples.md): complete agent functions you can adapt
