Functions

Run custom JavaScript code from RevCent triggers, APIs, webhooks, schedules, AI tools, and payment flows.

RevCent Functions allows you to run your own custom JavaScript code based on triggers that occur related to your RevCent account. The code is hosted and run by RevCent when specific triggers match your function(s) settings.

Why Use A RevCent Function?

View Functions

View your functions by clicking Tools > Functions > All Functions in the sidebar, or go to https://revcent.com/user/functions.

Functions list

Create A Function

If you have not requested access to RevCent Functions, you will need to do so.

Create a new function by clicking the Create New Function button when viewing all functions or go to https://revcent.com/user/new-function.

Create function

Name

Enter a name for the function. Required.

Description

Enter a description for the function.

Once the function is created you will be forwarded to the Edit Function Page for the new function. Continue to the Edit A Function section below.

Edit A Function

Edit an existing function by clicking the edit icon when viewing all functions.

Details

Function details

Name

Enter a name for the function. Required.

Description

Enter a description for the function.

Status

Set the status for the function.

Trigger

The function trigger is what initiates a function run. Please read the Function Trigger section for details on each trigger.

Trigger

Select the function trigger.

Options:

  1. Account Event
  2. Schedule
  3. URL
  4. Webhook
  5. Email Template
  6. API/AI
  7. Payment Profile

Code

The language used is JavaScript, and the code is run within a NodeJS 22.x runtime. Write your own custom JavaScript code that will execute based on the trigger that occurred. Please read the sections below on the Execution Environment and Execution Handler for information on how your function code is ultimately run.

Function code editor

Code Editor

The RevCent Functions code editor is Monaco, the same editor that powers VS Code. Type checking, error detection and more are built into the editor.

Function Environment Variables

You have the ability to add environment variables which are specific to the function and are accessible via the process.env object within your code.

Note: Environment variables added within the function take precedence over Function Values. If an environment variable within a function shares the same name as a Function Value, then the functions’ environment variable will replace the Function Value for the same name.

Function environment variables

Add Variable

Click the Add Environment Variable button to create a new variable for the specific function. You have the option to encrypt an environment variable for sensitive data.

Note: Remember to save your function after adding or encrypting variables.

Function Trigger

The function trigger is what causes the function run, and determines the event.data property within the function execution. There are key differences in each trigger option.

Trigger Options:

  • Account Event: Function is triggered by RevCent automatically when a specific event occurs.
  • Schedule: Function is triggered by RevCent on a fixed schedule using a cron expression.
  • URL: Trigger the function with a response determined by the function. Useful for performing immediate operations or requesting data.
  • Webhook: Send a notification to the function with an empty response. Useful for allowing third parties to post data.
  • API/AI: Trigger the function using the RevCent API, as an AI System Tool, as a Filter Function or as a Pre-Agent function.
  • Email Template: Generate custom data for an Email Template.
  • Payment Profile: Run a function during the processing of a Next-Gen payment profile.

Account Event

The Account Event trigger allows you to have RevCent automatically run a function when a specific event occurs. Extremely useful for processing an item when created or updated. For example, you can run custom logic when a sale is created, a subscription renewed, etc.

The event.data property will contain details on the specific item related to the event, in JSON format.

Important: Please view the Events page for more information on what item type is associate for each event notation, and a description of each as well.

Account event trigger

When editing a function and selecting Account Event as the Trigger, additional options will appear.

Campaign filter

Campaign Filter

Select one or more campaign(s) to filter only triggers from originating campaign(s). If a campaign(s) is selected, the function will trigger only from the campaign(s) selected. If none selected, the function will trigger regardless of originating campaign. Optional.

Shop filter

Shop Filter

Select one or more shops(s) to filter only triggers from originating shops(s). If a shops(s) is selected, the function will trigger only from the shops(s) selected. If none selected, the function will trigger regardless of originating shop. Optional.

Account event selector

Account Event(s)

Select one or more Account Event(s), any of which will trigger the function. Please view the Events page for more information on what an event is, event notations and examples.

Email Template

The Email Template trigger allows you to execute the function during the compilation of an Email Template to generate a custom_data object. The function will receive the details of the item specific to the email template triggered at time of compilation. The items’ details is contained in the event.data.item_details object. View the email template trigger list to see the event.item_details that corresponds to each.

Important: The function must return a valid JSON object in order to be amended to the email templates’ input data as custom_data, i.e. return {"custom_property": "custom_value"}; or callback(null, {"custom_property": "custom value"});

Email template trigger

Payment Profile

The Payment Profile trigger allows you to execute the function during the processing of a Next-Gen payment profile flow. The function will receive the specific flow request object, and allows you to run it separately or return a response. Read more about the Next-Gen Run Function node, including the item details object and response object requirements.

Payment profile trigger

API/AI

The API/AI trigger allows you to trigger the function directly via the RevCent API, have AI trigger the function via System Tools, utilize the function as a filter or generate custom content as a Pre-Agent function. This is especially useful when using AI System Tools. The AI can trigger a function on it’s own or when told and provide custom arguments to the function when triggered.

API AI trigger custom arguments

Trigger Sources

When setting the trigger to API/AI, there are several source types which can trigger the function:

Custom Arguments

Note: Custom arguments are only used when AI is calling a function via AI System Tools, and not during a direct API request via Filter Function or Pre-Agent Function.

Custom arguments allow you to pass dynamically generated information from AI into the function as the event.data.custom_arguments object. You specify the name and description of each argument. The AI will read a custom arguments’ description, generate a value for it and then set the name and value within the event.data.custom_arguments object. This allows you to have the AI use its own logic to generate custom data the function will receive. Your function code can access the custom argument value the AI generated via event.data.custom_arguments[argument_name].

Important: Please read more in detail about Custom Arguments.

Schedule

The schedule trigger allows you to execute the function on a fixed schedule using a cron expression. The event.data property will be an empty string.

When editing a function, if you select Schedule as the Trigger, you must select a timezone and enter a valid cron expression.

Schedule trigger

Timezone

Select a timezone for the cron expression. The timezone will determine the time when the function is triggered.

Cron Expression

The cron expression is the most important part of a Schedule trigger. You must enter a standard five-part cron expression:

  • Minutes: 0-59
  • Hours: 0-23
  • Day of Month: 1-31
  • Months: 0-11 (Jan-Dec)
  • Day of Week: 0-6 (Sun-Sat)

We recommend using the validate feature before attempting to save the function. The next 5 run dates will be displayed when validating.

Important things to note
  • Cron expression intervals cannot be less than 10 minutes apart. I.e. cannot schedule a function to run every 2 minutes, nor every 9 minutes, etc.
  • Scheduled functions are checked every 10 minutes, so exact minute execution can have up to a 10 minute variance. If exact timing is important, we recommend scheduling a cron expression to run on the x10th minute of an hour, i.e. at 04:00:00, 11:10:00, 16:20:00, etc.
  • Only standard five-part cron expressions supported, i.e. 0 8 * * *. The @ syntax is not supported.

URL

The URL trigger allows you to execute the function immediately using the functions’ URL, with either a GET or POST request, and receive a response determined by the function. Useful for performing immediate operations or requesting data.

The event.data property will be the body of the URL request, if present. The body will be in string format, allowing you to process any content type.

When editing a function, if you select URL as the Trigger, you have the option to create a new function URL if one has not been created. If already created, the function URL will appear.

Create function URL

Create Function URL

If you have not created a URL for the function, the Create New URL button will appear. Click the button and RevCent will create a custom URL to be used for triggering the function.

Function URL

Function URL

After creating a URL for the function, the URL will appear. This URL is what will immediately trigger the function without delay.

Function URL Response

Important: When a request is sent to the function URL, RevCent will return the response from the function execution. The URL trigger is meant as a request > function execution > function response. Therefore, you should consider implementing some form of authentication if returning sensitive data.

Function URL Authentication

Your function URL is publicly accessible. Other than IP restrictions, RevCent does not provide any authentication methods for function URL requests. You should always verify that the request to your function URL came from an authorized source. We recommend verifying requests by having a form of authentication built into your function code. You can utilize the request body or the headers and url parameters provided in the functions’ context object for authentication.

Webhook

The Webhook trigger allows the execution of the function using the functions’ webhook URL. You can perform actions and parse a webhook requests’ body when a POST request is sent to the functions’ webhook URL.

The event.data property will be the body of the webhook POST. It will be in string format, allowing you to process any content type.

When editing a function, if you select Webhook as the Trigger, you have the option to create a new webhook URL for the function if one has not been created. If already created, the webhook URL will appear.

Create webhook

Create Webhook

If you have not created the webhook within the function, the Create New Webhook button will appear. Click the button and RevCent will create a custom webhook endpoint to be used for triggering the function.

Webhook URL

Webhook URL

After creating a webhook for the function, the webhook URL will appear. This URL is what will trigger the function. Note: only POST requests to the webhook URL will be processed.

Webhook Response

Important: When a request is sent to the webhook URL, RevCent does not return a response from the function execution. With the webhook trigger, RevCent will always reply with status 200 OK and a static response acknowledging the POST request. This allows third parties to POST data to your webhook without receiving a response containing sensitive data.

Static Response:

Status 200 OK

text
{
    "result": "OK"
}
Webhook Authentication

Your webhook URL is publicly accessible. Other than IP restrictions, RevCent does not provide any authentication methods for Webhook requests. You should always verify that the message posted to your webhook is authentic. We recommend verifying requests by having a form of authentication built into your function code. You can utilize the request body or the headers and url parameters provided in the functions’ context object for authentication.

Trigger Timing

By default, functions are executed immediately when the trigger occurs. However, you have the option to delay the function execution by a specified period of time.

Note: Trigger timing is only applicable for Account Event and Webhook triggers. The URL, Schedule and Email Template triggers execute immediately without delay.

Immediate timing

Immediate (default)

The default setting for Timing is immediate. This means when the trigger occurs, the function is executed without delay.

Delay timing

Delay

You can set a delay on the function execution for a minimum of 5 minutes to a maximum of 48 hours. Enter the amount of time and select the time unit. Unit can be minutes, hours or days.

IP Restrictions

You can restrict triggering a function to specific IP address. If enabled, only IP addresses listed will be able to post to the function Webhook or Function URL.

Note: IP restriction is only applicable to Webhook and URL triggers.

IP restrictions

IP Restricted

Indicate whether to implement IP restrictions.

IP Whitelist

If IP restricted is true, enter allowed IPv4 address on a new line. IP ranges are not supported.

Note: RevCent IP’s are 52.3.146.218 and 34.224.171.255 if you are performing cross function execution.

Function Values

Securely store values for use throughout all of your RevCent Functions. The values are turned into environment variables when the function is executed, and are accessible via the process.env object within your code. Function Values are intended as a way to share common values for use throughout all functions. Use function environment variables to store function specific values and sensitive data.

Note: Environment variables added within a specific function take precedence over Function Values. If an environment variable within a function shares the same name as a Function Value, then the function environment variable will replace the Function Value for the same name during code execution.

View your function values by clicking Integrations > Functions > Values in the sidebar, or go to https://revcent.com/user/function-values.

Function values

Create Function Value

Create a function value by clicking the Create New Function Value button when viewing all function values.

Create function value

Name

Enter the name for the value. The name is what you will use to access the value within the process.env object. For example, if the name is “my value”, you would access it in your code by using process.env['my value']

Value

The actual value. Values are securely stored by RevCent and are decrypted when the function is run.

Description

Write an optional description to remind yourself what the value is for.

Execution Environment

Each function is run (executed) in a secure virtual environment, using NodeJS 22.x. Functions do not share/store data or state across function runs. There are several important things to note regarding the function, including the handler, dependencies and limitations.

All external requests sent from a RevCent Function will have the following IP address: 52.3.146.218

Environment Variables

The process.env object is where function environment variables and Function Values are stored for use within a function. Before execution, your secure Function Values are decrypted and set as individual environment variables. Environment variables added within a specific function take precedence over Function Values. If an environment variable within a function shares the same name as a Function Value, then the functions’ environment variable will replace the Function Value for the same name.

For example, if you have a Function Value named “My Value”, you would access it via process.env['My Value']. However, if you had a function environment variable with the same name “My Value”, then the function environment variable will take precedence.

Limitations

Below are the limitations with RevCent Functions.

  • You must initially contact RevCent to enable Functions for your account.
  • 5 functions per account. You can request an increase if necessary.
  • 1000 function runs, per function, per 24 hour period. You can request an increase if necessary.
  • 15 second function run time limit. Functions exceeding 15 seconds will timeout, causing an error.
  • Must use require() for dependencies in function code. ESM imports are not allowed and will cause errors.
  • Only string values will be logged to the console. JSON.stringify objects or arrays.
  • Neither data nor state is guaranteed to be persisted between function executions.
  • Functions resulting in too many execution errors will be automatically disabled.

Dependencies

RevCent Functions allows you to use any dependency you wish. Simply include the dependency in your list of dependencies and they will be installed when provisioning your function.

How It Works

Each function has a specific package.json. When you modify a functions’ package.json, RevCent will install the dependencies specific to the function. Once the function has been provisioned and is ready, the dependencies will be available for use within the functions’ code via require().

Note: When modifying the package.json, allow up to 5 minutes for the new dependencies to be installed and available for use.

Package Editor

When modifying your function, click the Dependencies tab to view the functions’ package.json. It is important to ensure the package version is correct, or use latest as the version. Incorrect dependency versions will cause a provisioning error.

Package editor

Execution Handler

When RevCent runs your function, your code is expected to have an exports.handler function. Failure to include the handler will result in the function not being executed. The handler has two main arguments, event, context and an optional third callback argument. Ensure your function code either uses a callback, return or throw to end function execution.

Example of a handler with the function ending execution with a return success.

javascript
exports.handler = async function(event, context) {
  return 'OK';
};

Example of a handler with the function ending execution with an error.

javascript
exports.handler = async function(event, context) {
  throw new Error('Something failed.');
};

Example of a handler with the function ending execution with a callback success.

javascript
exports.handler = async function(event, context, callback) {
  callback(null, 'Success');
};

Example of a handler with the function ending execution with a callback error.

javascript
exports.handler = async function(event, context, callback) {
  callback('Error occured.');
};

Event Argument

The event argument is an object containing the data object.

The event.data object is the actual data specific to trigger that executed the function. Refer to the table below as to the contents of the event.data object.

Trigger context.source.trigger event.data Format
Account Event account_event Information specific to the account event, including the event date and item details. The items’ details is contained in the event.data.item_details object. View the Events page for more information. JSON
Schedule schedule A schedule trigger has an empty event.data string. String
Webhook webhook Webhook request body, as a string. Parse the request body based on the context.source.content_type. String
URL function_url Function URL request body, as a string. Parse the request body based on the context.source.content_type. String
Email Template email_template Information specific to the compilation of the email template. The items’ details is contained in the event.data.item_details object. The item is dependent on the Email Template trigger. For example, a sale email template trigger will be a sale event object. Important: The function must return a valid JSON object in order to be amended to the input data as custom_data, i.e. return {"custom_property": "custom value"}; or callback(null, {"custom_property": "custom value"}); JSON
API/AI api: api_call
ai_web_chat: tool_call
ai_assistant: tool call | filter function
ai_voice_agent: tool call | filter function | pre_agent_function
Determine source type via context.source.type.

api_call: If triggered directly by using the function trigger operation in an API request, the event.data.item_details will be present if an item_type and item_id is provided in the request body.

tool_call: If triggered as an AI Tool Call, custom arguments will be contained within the event.data.custom_arguments object.

filter_function: If triggered as a Filter Function, the event.data.item_details will be present and contain the specific event item details that triggered the AI Assistant or AI Voice Agent.

pre_agent_function: If triggered as a Pre-Agent Function, the event.data.item_details will be present and contain the specific event item details that triggered the AI Voice Agent. An inbound AI Voice Call item details will always be the customer details if a successful customer match is found using inbound phone number.
JSON
Payment Profile payment_profile Please read the details on the Next-Gen Payment Profile event data. JSON

Account Event Object

Below is an example event argument object for an Account Event trigger. View examples of the event.data object for all account event item types on the Events Page.

javascript
{
    "data": {
        "event_date": "2022-05-26T17:28:28.598Z", // Date the event took place
        "event_id": "vE0Wk9omQPHRo5RMRXvK", // The account event ID
        "event_notations": [ // All event notation(s).
            "sale.created.success"
        ],
        "event_trigger": "sale.created.success", // Notation which triggered the function.
        "item_type": "sale", // The item type related to the event
        "item_id": "nbO1jv0On1ukzvdg1lNz", // The ID of the item
        "item_event": "created", // The item event
        "item_details": {} // The details of the item, corresponds to the item_type. Would be sale details in this example.
    }
}

Schedule Event Object

Below is an example event object for a Schedule trigger.

javascript
{
    "data": "" // Schedule trigger data is always an empty string.
}

Webhook Event Object

Below is an example event object for a Webhook trigger.

javascript
{
    "data": "{\"test\": \"webhooktest\"}" // Webhook trigger data is always a string. Parse string according to context.source.content_type
}

URL Event Object

Below is an example event object for a URL trigger.

javascript
{
    "data": "{\"test\": \"urltest\"}" // URL trigger data is always a string. Parse string according to context.source.content_type
}

Email Template Object

Below is an example event object for an Email Template trigger.

javascript
{
    "data": {
        "item_type": "customer",
        "item_id": "Q4nGRNpLgpS92QqGLwlX",
        "item_details": { // The details of the item, corresponds to the item_type. Would be customer details in this example.
            "address_line_1": "1600 Pennsylvania Ave",
            "address_line_2": "",
            ...
        }
    }
}

API Object

Below is an example event object for an API triggered function that also contains and item_type and item_id in the request.

javascript
{
    "data": {
        "item_type": "customer",
        "item_id": "Q4nGRNpLgpS92QqGLwlX",
        "item_details": {
            "address_line_1": "1600 Pennsylvania Ave",
            "address_line_2": "",
            ...
        },
        "custom_arguments": {
            "customer_card_id": "XKob65Bn8qfqmWggp99B",
            "customer_card_type": "VISA"
        }
    }
}

AI Tool Call Object

Below is an example event object for an AI tool call triggered function. Notice the custom_arguments object. Read more about Custom Arguments.

javascript
{
    "data": {
        "item_type": "customer",
        "item_id": "Q4nGRNpLgpS92QqGLwlX",
        "item_details": {
            "address_line_1": "1600 Pennsylvania Ave",
            "address_line_2": "",
            ...
        },
        "custom_arguments": {
            "customer_card_id": "XKob65Bn8qfqmWggp99B",
            "customer_card_type": "VISA"
        }
    }
}

Filter Function Object

Below is an example event object for a filter function. The event.data.item_details will contain the specific event item details that triggered the AI Assistant or AI Voice Agent.

javascript
{
    "data": {
        "item_type": "customer",
        "item_id": "Q4nGRNpLgpS92QqGLwlX",
        "item_details": {
            "address_line_1": "1600 Pennsylvania Ave",
            "address_line_2": "",
            ...
        }
    }
}

AI Voice Agent Pre-Agent Function Object

Below is an example event object for a pre-agent function within an AI Voice Agent. The event.data.item_details will contain the specific event item details that triggered the AI Voice Agent, if applicable. An inbound AI Voice Call item details will always be the customer details if a successful customer match is found using inbound phone number.

javascript
{
    "data": {
        "item_type": "customer",
        "item_id": "Q4nGRNpLgpS92QqGLwlX",
        "item_details": {
            "address_line_1": "1600 Pennsylvania Ave",
            "address_line_2": "",
            ...
        }
    }
}

Payment Profile Object

Please read the Next-Gen Payment Profile section on function event data when triggered via a payment flow.

Context Argument

The context argument is an object containing data related to the function run.

context. Description
source The source object containing details on the source of the function execution.
source.id The ID of the source. I.e. the ID of the event, webhook, function, API account, AI Web Chat, AI Assistant, AI Voice Agent or email template.
source.name The name of the source. [1]
source.trigger The function trigger. Values: api, account_event, webhook, function_url, ai_web_chat, ai_assistant, ai_voice_agent, email_template.
source.type The function type. [3] Values: api_call, tool_call, filter_function, pre_agent_function
source.method The originating request method, GET or POST. [2]
source.content_type The originating request content type, useful for parsing event.data. [2]
source.ip_address The originating request IP address. [2]
source.headers An objecting containing the originating request headers. [2]
source.url_params An objecting containing the originating request URL parameters. [2]
source.ai_voice_call The AI Voice Call object if the function is triggered as a pre-agent function prior to a call or as a system action via an AI Voice Agent.
source.ai_voice_call.id The AI Voice Call ID.
source.ai_voice_call.call_method The AI Voice Call method, either “inbound” or “outbound”.
source.ai_voice_call.from The AI Voice Call from phone number.
source.ai_voice_call.to The AI Voice Call to phone number.
function The function object containing details of the function being run.
function.id The ID of the function being run.
function.name The name of the function being run
function_run The function_run object containing details on the individual function run
function_run.id The ID of the individual function run.
dependencies An object containing the list of dependencies available, to use as a reference.

[1] Applicable to webhook, API, AI Web Chat, AI Assistant, AI Voice Agent and email template triggers only.

[2] Applicable to webhook and function URL triggers only.

[3] Applicable to API, AI Web Chat, AI Assistant and AI Voice Agent triggers only.

Account Event Context Object

Below is an example context object for an Account Event trigger.

javascript
{
    "source": {
        "id": "Q4l5oV0nvdt9ERJYLgGb",
        "name": "Account Event",
        "trigger": "account_event"
    },
    "function": {
        "id": "Wm4noL2AEji2PolWo6qK",
        "name": "Account Event Function"
    },
    "function_run": {
        "id": "Q4l5oWG9rMuJAQkz0NzR"
    },
    "dependencies": {}
}

Schedule Context Object

Below is an example context object for a Schedule trigger.

javascript
{
    "source": {
        "id": "MWOKkZlYNKCwnZLqALbr",
        "name": "Schedule Function",
        "trigger": "schedule"
    },
    "function": {
        "id": "MWOKkZlYNKCwnZLqALbr",
        "name": "Schedule Function"
    },
    "function_run": {
        "id": "Knl51G4Rdgs54VBJRpJ9"
    },
    "dependencies": {}
}

Webhook Context Object

Below is an example context object for a Webhook trigger.

javascript
{
    "source": {
      "id": "p2VEMp6REbvngimR2jvE",
      "name": "Webhook Function",
      "trigger": "webhook",
      "method": "POST",
      "content_type": "application/json",
      "ip_address": "1.2.3.4",
      "headers": {},
      "url_params": {}
    },
    "function": {
      "id": "vEgimR2jv6REbp2VEMpn",
      "name": "Webhook Function"
    },
    "function_run": {
      "id": "2rWZ9oMgYGsLvAnNKpy2"
    },
    "dependencies": {}
}

URL Context Object

Below is an example context object for a URL trigger.

javascript
{
    "source": {
        "id": "8rbjNL9rbkC8gw2OAa6k",
        "name": "Get Subscription",
        "trigger": "function_url",
        "method": "POST",
        "content_type": "application/json",
        "ip_address": "1.2.3.4",
        "headers": {},
        "url_params": {}
    },
    "function": {
        "id": "8rbjNL9rbkC8gw2OAa6k",
        "name": "Get Subscription"
    },
    "function_run": {
        "id": "6rlg462oL0HBbbW5wO95"
    },
    "dependencies": {}
}

Email Template Context Object

Below is an example context object for an Email Template trigger.

javascript
{
    "source": {
      "id": "ajzW4V4l8vtYWlqOoKj1",
      "name": "New Sale Email",
      "trigger": "email_template"
    },
    "function": {
      "id": "6rQ24og16BuJgmdqyqVq",
      "name": "Email Template Function"
    },
    "function_run": {
      "id": "l402L1qBy7CRZX2P7APL"
    },
    "dependencies": {}
  }

API Context Object

Below is an example context object for a direct API trigger, unrelated to an AI Assistant or AI Voice Agent.

javascript
{
    "source": {
        "id": "P6jO1qXVLlFY9567l284",
        "name": "My API Account",
        "trigger": "api",
        "api_call_id": "yRN5Jvj8M5IJarlblPBo",
        "ip_address": "1.2.3.4",
        "type": "api_call"
    },
    "function": {
        "id": "n62m9N4OX0hMB1V8mpYB",
        "name": "My Function"
    },
    "function_run": {
        "id": "5R5m6WlJlbsy90WXMYpG"
    },
    "dependencies": {}
}

AI Assistant Context Object

Below is an example context object for an AI Assistant triggered function. Notice how source.type can be one of two values, depending on how the function was triggered.

javascript
{
    "source": {
        "id": "XfKjYMwYAvj0qYkm0P12",
        "name": "My AI Assistant",
        "trigger": "ai_assistant",
        "api_call_id": "yRN5Jvj8M5IJarlblPBo",
        "ip_address": "1.2.3.4",
        "type": "tool_call | filter_function"
    },
    "function": {
        "id": "n62m9N4OX0hMB1V8mpYB",
        "name": "My Function"
    },
    "function_run": {
        "id": "5R5m6WlJlbsy90WXMYpG"
    },
    "dependencies": {}
}

AI Voice Agent Context Object

Below is an example context object for an AI Voice Agent triggered function. Notice how source.type can be one of three values, depending on how the function was triggered. The AI Voice Call object is present for tool_call and pre_agent_function source types only and not when a filter_function.

javascript
{
    "source": {
        "id": "m0P12YMwYXfKjAvj0qYk",
        "name": "My AI Voice Agent",
        "trigger": "ai_voice_agent",
        "api_call_id": "yRN5Jvj8M5IJarlblPBo",
        "ip_address": "1.2.3.4",
        "type": "tool_call | filter_function | pre_agent_function",
        "ai_voice_call": {
            "id": "0RzPnpPWK5iRaOgmGjyq",
            "call_method": "inbound",
            "from": "+12345678901",
            "to": "+17895761412"
        }
    },
    "function": {
        "id": "n62m9N4OX0hMB1V8mpYB",
        "name": "My Function"
    },
    "function_run": {
        "id": "5R5m6WlJlbsy90WXMYpG"
    },
    "dependencies": {}
}

Callback Argument

The callback argument is optional if you wish to use a callback to end the function execution. Note: You can also end a function execution using a return, throw, promise resolve or promise reject.

The callback function contains two arguments, error and response.

javascript
callback(error, response);
End with Error

Will end the function with the error returned.

javascript
callback('Something went wrong.');
End with Success

Will end the function as successful with the response returned. Notice the error argument is NULL.

javascript
callback(null, 'OK');

Code Examples

Below are code examples, showing how you would implement the function handler and end execution, as well as require dependencies.

Log Event

A simple function that logs the function event and sends back a basic response using a callback to end the function execution.

javascript
exports.handler = async function(event, context, callback) {
    console.log(event);
    callback(null, {
        response: "Hello World"
    });
};

Send Remote Request

A simple function that sends a remote request and uses a return to end the function execution. The function dependencies should include the axios library. Notice how we require the dependency outside of the handler.

javascript
const axios = require('axios');

exports.handler = async function(event, context) {
    try {
        const response = await axios.get('https://endpoint.example.com/api/data');
        return {
            response: response.data,
        };
    } catch (error) {
        throw new Error('Something failed.');
    }
};