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

# Create Function or Macro

> Creates a JavaScript function or a Jinja macro. Guardrails use them as checks (`CHECK`, in `lookFor`) or actions (`ACTION`, in `behaviour`); prompts call `HELPER` macros by name, as `{{ <name>(...) }}`. The code is checked when you save it. A call gets only the agent's active functions and macros: assign them with `PUT /v2/voice-agents/{voiceAgentId}/functions-macros`, or with `functionMacroIds` when you create a v2 agent (updating an agent does not change its assignments). Try code first with `POST /v2/voice-agents/functions-macros/test`.



## OpenAPI

````yaml /api-reference/openapi.json post /v2/voice-agents/functions-macros
openapi: 3.0.1
info:
  title: Hamsa API
  description: >-
    The Hamsa API: voice agents and their calls, phone numbers, batch calls and
    knowledge bases; speech to text, text to speech, voices and AI content.
  license:
    name: MIT
  version: 1.0.0
servers:
  - url: https://api.tryhamsa.com
security: []
paths:
  /v2/voice-agents/functions-macros:
    post:
      summary: Create a function or macro
      description: >-
        Creates a JavaScript function or a Jinja macro. Guardrails use them as
        checks (`CHECK`, in `lookFor`) or actions (`ACTION`, in `behaviour`);
        prompts call `HELPER` macros by name, as `{{ <name>(...) }}`. The code
        is checked when you save it. A call gets only the agent's active
        functions and macros: assign them with `PUT
        /v2/voice-agents/{voiceAgentId}/functions-macros`, or with
        `functionMacroIds` when you create a v2 agent (updating an agent does
        not change its assignments). Try code first with `POST
        /v2/voice-agents/functions-macros/test`.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - name
                - type
                - usedAs
                - code
              properties:
                name:
                  type: string
                  minLength: 1
                  maxLength: 255
                  description: >-
                    Name (1-255 characters), unique in the project. A `HELPER`
                    macro's name must be an identifier: letters, digits and
                    underscores, not starting with a digit
                    (`FunctionMacroHelperNameInvalid`), and its `code` must
                    define `{% macro <name>(...) %}` with this name. For any
                    macro written as definitions, the one named like the record
                    runs (else the first).
                notes:
                  type: string
                  maxLength: 2000
                  nullable: true
                  description: Your own notes. Not used on calls.
                type:
                  type: string
                  enum:
                    - JAVASCRIPT_FUNCTION
                    - JINJA_MACRO
                  description: >-
                    `JAVASCRIPT_FUNCTION`: the body of `function (text, vars) {
                    ... }`. `JINJA_MACRO`: a Jinja template with `text`, `vars`
                    and `args` in scope, or a `{% macro <name>(...) %}`
                    definition.
                usedAs:
                  type: string
                  enum:
                    - CHECK
                    - ACTION
                    - HELPER
                  description: >-
                    `CHECK`: answers "does this text match?" (a guardrail's
                    `lookFor`). `ACTION`: answers "what changes?" (a guardrail's
                    `behaviour`): new text, or variables to set. `HELPER`: a
                    macro prompts call by its name, as `{{ <name>(...) }}`
                    (`JINJA_MACRO` only).
                code:
                  type: string
                  minLength: 1
                  maxLength: 20000
                  description: >-
                    The code (1-20,000 characters), compiled when you save it.


                    **Function**: the body of `function (text, vars) { ... }`.
                    `text` is what was said, as said; `vars` are the call's
                    variables, as text unless a value is JSON. A `CHECK` returns
                    `true` to match. An `ACTION` returns a string (the new text)
                    or an object (the variables to set). JavaScript built-ins
                    only (no `console`, `fetch` or timers); 50 ms and 16 MiB per
                    run.


                    **Macro**: a template with `text`, `vars` and `args`, or a
                    `{% macro <name>(...) %}` definition (required for `HELPER`,
                    named like the record). A `CHECK` matches unless it renders
                    empty, `false`, `0`, `none` or `no`. An `ACTION` sets
                    variables when it renders a JSON object; anything else is
                    the new text. 50 ms and 64 KiB of output.
                params:
                  type: array
                  nullable: true
                  maxItems: 20
                  items:
                    type: string
                    maxLength: 64
                    pattern: ^[A-Za-z_][A-Za-z0-9_]*$
                  description: >-
                    `HELPER` macros only, and optional: the parameters that the
                    `{% macro <name>(...) %}` in `code` declares, in order.
                    Hamsa reads them from the code; if you send them they must
                    match it (`FunctionMacroParamsMismatch`). Leave out or
                    `null` for `CHECK` and `ACTION`.
            examples:
              js_check:
                summary: JavaScript check
                value:
                  name: has_card_number
                  type: JAVASCRIPT_FUNCTION
                  usedAs: CHECK
                  code: return /\d{13,19}/.test(text.replace(/[\s-]/g, ''));
                  notes: Matches 13 to 19 digits in a row
              js_action:
                summary: 'JavaScript action: set variables'
                value:
                  name: count_strike
                  type: JAVASCRIPT_FUNCTION
                  usedAs: ACTION
                  code: >-
                    return { guardrail_strikes: (Number(vars.guardrail_strikes)
                    || 0) + 1 };
              js_action_text:
                summary: 'JavaScript action: rewrite the text'
                value:
                  name: mask_card_number
                  type: JAVASCRIPT_FUNCTION
                  usedAs: ACTION
                  code: return text.replace(/\d(?=(?:[\s-]?\d){4})/g, '*');
                  notes: Keeps the last 4 digits
              macro_check:
                summary: Jinja check
                value:
                  name: says_yes
                  type: JINJA_MACRO
                  usedAs: CHECK
                  code: '{{ text.strip() in [''yes'', ''sure'', ''ok''] }}'
              macro_action:
                summary: 'Jinja action: set variables'
                value:
                  name: flag_for_review
                  type: JINJA_MACRO
                  usedAs: ACTION
                  code: '{"needs_review": true}'
              macro_action_text:
                summary: 'Jinja action: rewrite the text'
                value:
                  name: spell_out_brand
                  type: JINJA_MACRO
                  usedAs: ACTION
                  code: '{{ text | replace(''HB'', ''Hamsa Bank'') }}'
              macro_helper:
                summary: Jinja helper for prompts
                value:
                  name: greet
                  type: JINJA_MACRO
                  usedAs: HELPER
                  code: >-
                    {% macro greet(first_name) %}Hello {{ first_name }}, how can
                    I help?{% endmacro %}
      responses:
        '201':
          description: Created
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                    example: true
                  message:
                    type: string
                    example: success
                  data:
                    $ref: '#/components/schemas/FunctionMacro'
        '400':
          description: >-
            Invalid body: for example `HELPER` with a `JAVASCRIPT_FUNCTION`
            (`FunctionMacroHelperMacrosOnly`), `params` on a `CHECK` or `ACTION`
            (`FunctionMacroParamsHelperOnly`), a `HELPER` whose `code` does not
            define `{% macro <name>(...) %}` with its name
            (`FunctionMacroHelperDefinitionRequired`), a definition with more
            than 20 parameters, a parameter over 64 characters or a repeated one
            (`FunctionMacroParamsMaxLength`, `FunctionMacroParamInvalid`,
            `FunctionMacroParamsDuplicate`), `params` that differ from the
            definition's (`FunctionMacroParamsMismatch`), or code that does not
            compile (`FunctionMacroCodeSyntaxError`, with the reason and line in
            `params.reason` and `params.line`).
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorSchema'
        '401':
          description: 'Unauthorized: missing or invalid API key.'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorSchema'
        '403':
          description: >-
            Your API key or role does not have the `functions_macros:create`
            permission.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorSchema'
        '409':
          description: >-
            Another function or macro in the project has this name
            (`FunctionMacroNameAlreadyExists`).
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorSchema'
        '500':
          description: Server Side Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorSchema'
        '503':
          description: >-
            The code could not be checked right now
            (`ScriptExecutorUnavailable`). Try again later.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorSchema'
      security:
        - ApiKeyAuth: []
components:
  schemas:
    FunctionMacro:
      type: object
      description: 'A project script: a guardrail check or action, or a prompt helper macro.'
      properties:
        id:
          type: string
          format: uuid
          example: 9c1d2e3f-4a5b-4c6d-8e7f-0a1b2c3d4e5f
        projectId:
          type: string
          format: uuid
          example: fbb9e8b2-2dbb-40f9-a051-9404624e3247
        userId:
          type: string
          nullable: true
          example: b7d9e979-4a16-437b-8571-4ed92a94faa8
        createdBy:
          type: string
          description: ID of the member who created it.
          example: b7d9e979-4a16-437b-8571-4ed92a94faa8
        updatedBy:
          type: string
          nullable: true
          description: ID of the member who last changed it.
          example: null
        name:
          type: string
          minLength: 1
          maxLength: 255
          description: >-
            Unique among the project's functions and macros. A `HELPER` macro's
            name is how prompts call it: `{{ <name>(...) }}`.
          example: has_card_number
        notes:
          type: string
          maxLength: 2000
          nullable: true
          description: Your own notes. Not used on calls.
          example: Matches 13 to 19 digits in a row
        type:
          type: string
          enum:
            - JAVASCRIPT_FUNCTION
            - JINJA_MACRO
          description: >-
            `JAVASCRIPT_FUNCTION`: the body of `function (text, vars) { ... }`.
            `JINJA_MACRO`: a Jinja template with `text`, `vars` and `args` in
            scope, or a `{% macro <name>(...) %}` definition.
          example: JAVASCRIPT_FUNCTION
        usedAs:
          type: string
          enum:
            - CHECK
            - ACTION
            - HELPER
          description: >-
            `CHECK`: answers "does this text match?" (a guardrail's `lookFor`).
            `ACTION`: answers "what changes?" (a guardrail's `behaviour`): new
            text, or variables to set. `HELPER`: a macro prompts call by its
            name, as `{{ <name>(...) }}` (`JINJA_MACRO` only).
          example: CHECK
        code:
          type: string
          minLength: 1
          maxLength: 20000
          description: >-
            The code. A function is the body of `function (text, vars) { ... }`.
            A macro is a template, or a `{% macro <name>(...) %}` definition
            (always a definition named like the record for `HELPER`).
          example: return /\d{13,19}/.test(text.replace(/[\s-]/g, ''));
        params:
          type: array
          nullable: true
          maxItems: 20
          items:
            type: string
            maxLength: 64
            pattern: ^[A-Za-z_][A-Za-z0-9_]*$
          description: >-
            `HELPER` macros only: the parameters its `{% macro <name>(...) %}`
            definition declares, in order. `null` for `CHECK` and `ACTION`.
          example: null
        requiredParams:
          type: array
          nullable: true
          readOnly: true
          items:
            type: string
          example:
            - name
          description: >-
            `HELPER` macros only: the parameters without a default value, in
            order; a prompt must pass these. `{% macro greet(name, tone="warm")
            %}` gives `params` `[name, tone]` and `requiredParams` `[name]`.
            `null` for `CHECK` and `ACTION`.
        createdAt:
          type: string
          format: date-time
          example: '2026-10-20T09:15:00.000Z'
        updatedAt:
          type: string
          format: date-time
          example: '2026-10-20T09:15:00.000Z'
    ErrorSchema:
      type: object
      properties:
        code:
          type: integer
          description: >-
            Service error code: the HTTP status with a service prefix (for
            example `8404`). Missing when the service has no code for that
            status.
          example: 8404
        message:
          type: string
          description: >-
            What went wrong. Some services (calls and recordings) put the error
            key here, for example `CallNotFoundOrUnavailable`, and send no
            `messageKey`.
          example: Policy not found!
        messageKey:
          type: string
          description: >-
            Stable key for the error, safe to match on in code. Not returned by
            every service.
          example: PolicyNotFound
        params:
          type: object
          additionalProperties: true
          description: >-
            Details for some errors (for example `reason`). Not returned by
            every service.
          example:
            reason: NO_DRAFT
  securitySchemes:
    ApiKeyAuth:
      type: apiKey
      in: header
      name: Authorization
      description: >-
        Pass the API key in the Authorization header, You need to put Token
        keyword before the API key. e.g. 'Authorization: Token <api-key>'

````

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