> ## Documentation Index
> Fetch the complete documentation index at: https://docs.tryhamsa.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Functions & macros: custom checks and actions

> Write JavaScript functions and Jinja macros that guardrails check with or run, call macros from a flow step's text, try them out, and know their limits.

Functions & macros are small helpers you write once for the whole project. A guardrail uses one to decide whether something matches, or to change what was said and set variables. A macro can also be called from a flow step's text to build part of a message. Each helper is either a JavaScript function or a Jinja macro.

## Before you start

| Action | Owner | Admin | Member |
| - | - | - | - |
| Create and edit functions and macros | Yes | Yes | Yes |
| Add them to an agent, turn them on or off | Yes | Yes | Yes |
| Delete them from the library | Yes | Yes | No |

These are the role defaults. An owner can change them per member in [Roles and permissions](https://docs.tryhamsa.com/overview/projects/roles-and-permissions.md).

## Choose the type and use

| Type | Tag | Write it as |
| - | - | - |
| **JavaScript function** | JS | A function body that uses `text` and `vars`, and returns a value |
| **Jinja macro** | Jinja | A template over `text` and `vars`, rendered like your prompts. See [Jinja syntax](https://docs.tryhamsa.com/agents/variables/jinja.md). |

**Used as** decides where it runs:

| Used as | Where you pick it | What it must return |
| - | - | - |
| **Check** | Under **Look for** in a guardrail. "Matches when it returns true." | A function: exactly `true` to match. Anything else, `1` and `"true"` included, is an error. A macro matches unless it renders empty, false, 0, none or no. |
| **Action** | Under **What happens** in a guardrail (**Function or macro**) | Text, which replaces what was said, or the variables to set: an object from a function, a JSON object from a macro |
| **Use in prompts** | In a flow step's text. Macros only. "A guardrail can't pick it." | The text to put where it is called |

`text` is what was said. For a check it is cleaned up: digits in 0 to 9, Latin letters lowercased. For an action it is exactly as said. `vars` holds the call's [variables](https://docs.tryhamsa.com/agents/variables/overview.md).

## Create one

**1. Open Functions & macros**

In the sidebar, open **Functions & macros**. "JavaScript and Jinja helpers for guardrails and prompts. Shared across the project's agents." The **Yours** tab lists the project's helpers; **Built in** lists the ones that ship with Hamsa.

![The Functions & macros page, Yours tab, with JavaScript functions and Jinja macros, their use and the agents that use them](https://mintcdn.com/hamsa-452fa79a/IyoYQ-nNrFRmlJOT/images/agents/safety/functions-list-light.webp?fit=max\&auto=format\&n=IyoYQ-nNrFRmlJOT\&q=85\&s=f6981c9de74c43f5e995da52c54deb62)

**2. Click Create**

Start a blank function or macro, or a copy of a built-in one.

**3. Fill in the fields**

* **Name**: letters, digits and `_`, starting with a letter. Two macros can't share a name.
* **Type**: **JavaScript function** or **Jinja macro**.
* **Used as**: **Check**, **Action** or **Use in prompts**.
* **Code**: up to 20,000 characters.
* Notes: optional. "What it checks, for whoever uses it next." Up to 2,000 characters.

![A new JavaScript function used as Check, with its code and Try it showing that the sample would fire](https://mintcdn.com/hamsa-452fa79a/IyoYQ-nNrFRmlJOT/images/agents/safety/function-editor-try-it-light.webp?fit=max\&auto=format\&n=IyoYQ-nNrFRmlJOT\&q=85\&s=9643a9b64096fc7bf9f19e4e0b8d29de)

**4. Try it**

Under **Try it**, type a sample sentence and, if the code reads variables, the variables as JSON, for example `{"customer_id": "C-102"}`. For a check or an action, choose which side it checks: the caller's words or the agent's. For a macro used in prompts, fill in a value for each parameter. Click **Run**. You see what a call would do with the result (it trips or not, rewrites the text, sets variables, has no effect, or what it renders), the raw value the code returned, how long it took, and, under what the code saw, the exact text and variables it got. **Try it** runs on the same engines and limits as a call, so a result that a call would ignore shows here as an error that says why.

**5. Save**

Saving checks the code. "The code doesn't compile." means it has a syntax error.

## Examples

A check that fires when the caller mentions a six-digit order number:

```javascript theme={null}
return /order\s*#?\s*\d{6}/.test(text);
```

An action that flags the call for review and leaves the text as it is:

```javascript theme={null}
return { needs_review: true };
```

A macro check that fires when the caller says "refund":

```jinja theme={null}
{{ 'yes' if 'refund' in text else '' }}
```

## Add a helper to an agent

A guardrail only runs helpers that are on its agent. In the agent's settings (a single prompt agent's settings, or **Global settings** in a flow agent), open **Functions & macros**: "JavaScript and Jinja helpers guardrails check with or run". Add the helper and make sure it is switched on.

![An agent's Functions & macros settings with four helpers on this agent, each switched on](https://mintcdn.com/hamsa-452fa79a/IyoYQ-nNrFRmlJOT/images/agents/safety/agent-functions-macros-light.webp?fit=max\&auto=format\&n=IyoYQ-nNrFRmlJOT\&q=85\&s=df0763cadbb66e1528394466e8264cc7)

If a guardrail picks a helper that isn't on the agent, the editor warns: "\{name} isn't on this agent, so here it never runs." Picking a helper from inside an agent's guardrail adds it to that agent.

Like policies and guardrails, helpers are not part of a version: adding, switching or editing one changes live calls right away. An edit in the library applies to every agent using it.

## Call a macro from a flow step's text

A Jinja macro used as **Use in prompts** can be called from a flow step's text by its name:

```jinja theme={null}
{{ greet(first_name) }}
```

Keyword arguments work too: `{{ greet(first_name, tone="warm") }}`.

**1. Create the macro**

Set **Used as** to **Use in prompts**. The code is the whole macro definition, and its first line names it with the macro's name: `{% macro greet(first_name) %}`, then the body, then `{% endmacro %}`. The editor fills in that frame and keeps the name in step with the **Name** field. The parameters are read from the definition and shown next to the code. A macro takes at most 20 parameters, each up to 64 characters.

**2. Add it to the agent and switch it on**

"Offered in this agent's steps while it is on here."

**3. Call it in a step**

Type `{{ greet(first_name) }}` in the step's text, or pick it from the suggestions. What the macro renders goes into the text where it is called. Steps written with the older `{{ macros.greet(...) }}` form are updated to the new form when you open them in the editor; save the agent to keep the change. Until then, the old form renders empty on a call.

If a macro fails while a call renders the text, it renders empty, and the rest of the text is unaffected.

Prompt macros are offered in the text of a flow agent's steps.

## Limits

| Item | Limit |
| - | - |
| A function run | 50 ms of run time, and 16 MB of memory for the call. Past that, a check counts as no match and an action changes nothing. Functions can't make network requests: get outside data once in a flow Tool step and read it from `vars`. |
| A macro run from a guardrail | 50 ms |
| A macro called from a prompt | No time limit on a call (2 seconds in **Try it**) |
| What a macro renders | 64 KB |
| Code, and the sample text in **Try it** | 20,000 characters each |
| Variables | 64 KB as JSON |
| Notes | 2,000 characters |
| Prompt macro parameters | 20, each up to 64 characters |

What a function gets and returns:

* **The text** exactly as it was said: digits and letters aren't changed, so a check that should match Arabic digits has to handle them itself.
* **Variables** as text, so `vars.age` is `"30"`: compare it as text or turn it into a number with `Number()`. A value that looks like JSON (`{…}` or `[…]`) is read as JSON; a value starting with `+`, such as a phone number, never is. Variables without a value aren't passed. Checks and actions also get `vars._side` (`caller` or `agent`).
* **JavaScript built-ins only:** JSON, Math, Date (in UTC, not the agent's time zone), regular expressions with named groups and Unicode, Map, Set, classes, `?.` and `??`, and more. There's no `console`, `fetch`, `setTimeout` or other way to reach the network or files, and no `Intl`, `structuredClone`, `Array.prototype.at`, `findLast`, `toSorted` or `Object.hasOwn`.
* **A check** matches only when it returns exactly `true`. **An action** returns new text (a non-empty string) or an object of variables to set. A returned promise is never awaited.
* **Within a call,** functions share one context for the whole call, so a global variable set in one run is still there in the next. **Try it** starts fresh every time.

What works in a macro: Jinja's built-in filters and tests (`trim`, `lower`, `replace`, `split`, `join`, `tojson` and more); `range` and `lipsum` don't exist. A name that isn't set renders empty, but reading a field of one (`{{ missing.x }}`) is an error. A check macro matches unless what it renders is empty, `false`, `0`, `none` or `no`. An action macro that renders a JSON object sets those variables; anything else becomes the new text. Macros write no logs.

When a run fails, **Try it** says why: the code doesn't parse, it failed while running, it took too long, it used too much memory, it rendered too much, or it returned something a call would ignore. On a call the same failure is silent: a check counts as no match, an action changes nothing, and a macro in a prompt renders empty. A syntax error is refused when you save.

An action can't set `user_number`, `call_id`, `current_date` or `current_time`.

## Built-in functions and macros

Hamsa ships ready-made helpers under **Built in**. Their code isn't shown and can't be changed. To use one in a guardrail, open it and click **Use as template**: this saves a copy in your project that you can edit, and guardrails can use the copy. A built-in helper itself can't be used in a guardrail, only your copy.

> [accordion] Built-in functions
>
> | Name | What it checks or does |
> | - | - |
> | `hasPhoneNumber` | "Seven or more digits in a row, like a phone number." |
> | `hasEmail` | "An email address." |
> | `hasCardNumber` | "A card number: 13 to 19 digits that pass the Luhn check." |
> | `hasIban` | "An IBAN that passes its mod-97 check." |
> | `hasNationalId` | "A Saudi ID or Iqama number, or an Emirates ID." |
> | `hasOneTimeCode` | "A 4 to 8 digit code said next to a word like OTP, PIN, CVV, code or password." |
> | `hasPrice` | "A price: a currency next to a number, in English or Arabic." |
> | `hasLink` | "A web link." |
> | `hasMarkdown` | Markdown symbols or tags the voice would read out |
> | `hasEmoji` | "An emoji." |
> | `isLong` | "More than 40 words, too much to say in one go." |
> | `isArabic` | "Mostly Arabic." |
> | `isEnglish` | "Mostly English." |
> | `isFiller` | Only hesitation sounds, like "umm" or "امم", with no real answer |
> | `asksForHuman` | Asks for a person: a manager, a supervisor, customer service, "موظف" |
> | `hasInstructionOverride` | Tries to override the agent's instructions, like "ignore your instructions" |
> | `countStrike` | Adds one to `guardrail_strikes` each time it runs |
> | `flagForReview` | Sets `needs_review` to true, to find the call later |
> | `requestHuman` | Sets `wants_human` to true, for a transition to your hand-off step |
> | `saveFlaggedText` | Saves what set the guardrail off in `last_flagged_text` |
> | `maskPersonalData` | Replaces phone numbers, emails and IDs with `e_` codes. See [Protect personal data](https://docs.tryhamsa.com/agents/safety/personal-data.md). |
> | `unmaskPersonalData` | Turns `e_` codes back into the values right before the agent speaks |

> [accordion] Built-in macros
>
> | Name | What it checks or does |
> | - | - |
> | `said_nothing` | "The caller said nothing, or only spaces." |
> | `says_yes` | A plain yes, like "yes", "sure" or "ايوه" |
> | `says_no` | A plain no, like "no", "not now" or "لا" |
> | `short_answer` | "Two words or fewer." |
> | `over_strikes` | `guardrail_strikes` is 3 or more. Pair it with `count_strike` and **Disconnect**. |
> | `count_strike` | Adds one to `guardrail_strikes` each time it runs |
> | `flag_for_review` | Sets `needs_review` to true, to find the call later |
> | `mark_escalated` | Sets `escalated` to true, for a transition or the webhook to read |

## Good to know

* A check runs on everything said, so keep it fast.
* "It can't be deleted while it's in use." Take it off every guardrail and agent first.
* Variables an action sets are ordinary call variables: use them in [transitions](https://docs.tryhamsa.com/agents/flow/transitions.md), conditions and other guardrails.

## Related

> [card] [Policies & guardrails](https://docs.tryhamsa.com/agents/safety/policies-and-guardrails.md)
>
> Use functions and macros as checks and actions.

> [card] [Protect personal data](https://docs.tryhamsa.com/agents/safety/personal-data.md)
>
> The mask and unmask functions in practice.

> [card] [Jinja syntax](https://docs.tryhamsa.com/agents/variables/jinja.md)
>
> Templates in prompts and messages.

> [card] [Variables](https://docs.tryhamsa.com/agents/variables/overview.md)
>
> The values helpers read and set.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.