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

# Try Function or Macro

> Runs code on a sample `text` and `vars` the way a call runs it, without saving anything. Send `type`, `usedAs` and `code`, or the `functionMacroId` of a saved one (fields you also send replace its saved ones). `vars` reach the script as on a call: values as text unless JSON, empty ones left out. A `HELPER` is called like a prompt calls it, with `args` or with its parameters read from `vars`. A failing script still returns 200, with `error` set.



## OpenAPI

````yaml /api-reference/openapi.json post /v2/voice-agents/functions-macros/test
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/test:
    post:
      summary: Try a function or macro
      description: >-
        Runs code on a sample `text` and `vars` the way a call runs it, without
        saving anything. Send `type`, `usedAs` and `code`, or the
        `functionMacroId` of a saved one (fields you also send replace its saved
        ones). `vars` reach the script as on a call: values as text unless JSON,
        empty ones left out. A `HELPER` is called like a prompt calls it, with
        `args` or with its parameters read from `vars`. A failing script still
        returns 200, with `error` set.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                functionMacroId:
                  type: string
                  format: uuid
                  description: A saved function or macro to run.
                name:
                  type: string
                  minLength: 1
                  maxLength: 255
                  description: >-
                    For an unsaved macro: its name, which picks the `{% macro
                    %}` definition to run (left out: the first one in `code`). A
                    `HELPER` is called by this name.
                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`.
                side:
                  type: string
                  enum:
                    - caller
                    - agent
                  default: caller
                  description: >-
                    `CHECK` and `ACTION` only: the side a guardrail is checking,
                    passed to the script as `vars._side`. `caller`: what the
                    caller said. `agent`: the agent's reply.
                args:
                  type: array
                  maxItems: 20
                  items: {}
                  description: >-
                    `HELPER` only: the arguments of the prompt call, in order,
                    as in `{{ greet('Sara') }}`. Left out: each parameter is
                    read from `vars` by name.
                text:
                  type: string
                  maxLength: 20000
                  default: ''
                  description: What was said (up to 20,000 characters), used as sent.
                vars:
                  type: object
                  additionalProperties: true
                  default: {}
                  description: >-
                    The call's variables. Numbers and booleans reach the script
                    as text, as on a call; objects and arrays stay as they are.
            examples:
              unsaved_check:
                summary: Unsaved JavaScript check
                value:
                  type: JAVASCRIPT_FUNCTION
                  usedAs: CHECK
                  code: return /\d{13,19}/.test(text.replace(/[\s-]/g, ''));
                  text: My card is 4111 1111 1111 1111
              saved_action:
                summary: Saved action
                value:
                  functionMacroId: 2b3c4d5e-6f70-4812-9a3b-4c5d6e7f8091
                  text: cancel my order
                  vars:
                    guardrail_strikes: 1
              helper:
                summary: Unsaved helper macro, arguments from vars
                value:
                  name: greet
                  type: JINJA_MACRO
                  usedAs: HELPER
                  code: >-
                    {% macro greet(first_name) %}Hello {{ first_name }}, how can
                    I help?{% endmacro %}
                  vars:
                    first_name: Sara
              helper_args:
                summary: Unsaved helper macro, arguments as in the prompt
                value:
                  name: greet
                  type: JINJA_MACRO
                  usedAs: HELPER
                  code: >-
                    {% macro greet(first_name) %}Hello {{ first_name }}, how can
                    I help?{% endmacro %}
                  args:
                    - Sara
              agent_side_action:
                summary: Unsaved action on the agent's reply
                value:
                  type: JAVASCRIPT_FUNCTION
                  usedAs: ACTION
                  code: return text.replace(/\d(?=(?:[\s-]?\d){4})/g, '*');
                  side: agent
                  text: Your card 4111 1111 1111 1111 is on file.
      responses:
        '200':
          description: Successful response
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                    example: true
                  message:
                    type: string
                    example: success
                  data:
                    $ref: '#/components/schemas/FunctionMacroTestResult'
        '400':
          description: >-
            Invalid body, or neither `code` nor `functionMacroId` was sent
            (`FunctionMacroTestNeedsCode`), `side` is not `caller` or `agent`
            (`FunctionMacroTestSideInvalid`), `args` is not a list of at most 20
            values (`FunctionMacroTestArgsMustBeArray`), or the `HELPER` rules
            fail: 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`).
          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:read`
            permission.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorSchema'
        '404':
          description: >-
            Function or macro not found in this project
            (`FunctionMacroNotFound`).
          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 run right now (`ScriptExecutorUnavailable`).
            Try again later.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorSchema'
      security:
        - ApiKeyAuth: []
components:
  schemas:
    FunctionMacroTestResult:
      type: object
      description: >-
        What the code produced and what a call would do with it. A failing
        script still returns 200, with `error` set.
      properties:
        outcome:
          type: string
          enum:
            - TRIPPED
            - NOT_TRIPPED
            - TEXT_REWRITTEN
            - VARIABLES_SET
            - NO_OP
            - RENDERED
          description: >-
            What a call would do. `CHECK`: `TRIPPED` or `NOT_TRIPPED`. `ACTION`:
            `TEXT_REWRITTEN`, `VARIABLES_SET` or `NO_OP`. `HELPER`: `RENDERED`.
            With `error`: `NOT_TRIPPED` for a `CHECK`, `NO_OP` otherwise.
          example: TRIPPED
        returned:
          description: >-
            The raw result: what the function returned after passing through
            JSON, as on a call (`undefined` is left out, a date becomes its ISO
            text), or the text the macro rendered.
          example: true
        matched:
          type: boolean
          description: >-
            `CHECK` only: `true` when the check trips. A function trips only
            when it returns exactly `true`.
          example: true
        variables:
          type: object
          additionalProperties: true
          description: >-
            `ACTION` only: the variables it would set. Empty when it rewrites
            the text or fails.
          example:
            needs_review: true
        newText:
          type: string
          description: '`ACTION` only: the new text, when the script answered with text.'
          example: Your card **** **** **** 1111 is on file.
        rendered:
          type: string
          description: '`HELPER` only: what the macro rendered, called as a prompt calls it.'
          example: Hello Sara, how can I help?
        text:
          type: string
          description: '`text` as the script saw it: as sent.'
          example: My card is 4111 1111 1111 1111
        vars:
          type: object
          additionalProperties: true
          description: '`vars` as the script saw them, shaped as on a call.'
          example:
            guardrail_strikes: '1'
            _side: caller
            _guardrail_id: try-it
        durationMs:
          type: number
          description: How long the run took, in milliseconds.
          example: 3.2
        error:
          $ref: '#/components/schemas/FunctionMacroScriptError'
    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
    FunctionMacroScriptError:
      type: object
      description: Why the code failed.
      properties:
        kind:
          type: string
          enum:
            - SYNTAX
            - RUNTIME
            - TIMEOUT
            - MEMORY
            - OUTPUT_CAP
            - RESULT
          description: >-
            `SYNTAX`: does not compile. `RUNTIME`: threw an error. `TIMEOUT`:
            ran past the time limit (50 ms for a function or for a macro a
            guardrail runs). `MEMORY`: a function ran past 16 MiB. `OUTPUT_CAP`:
            a macro rendered more than 64 KiB, which a call discards. `RESULT`:
            returned a value a call would ignore, such as a check that returns
            something other than `true` or `false`, or an action that returns
            nothing or empty text.
          example: RUNTIME
        message:
          type: string
          example: 'ReferenceError: ''txt'' is not defined'
        line:
          type: integer
          nullable: true
          description: Line in the code, starting at 1, when known.
          example: 2
  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.