This document provides a reference for all system functions provided by Dialogflow.

You can apply inline system functions in your agent's
[conditions](https://docs.cloud.google.com/dialogflow/cx/docs/reference/condition#func),
[static response messages](https://docs.cloud.google.com/dialogflow/cx/docs/concept/fulfillment#static)
(such as
[text responses](https://docs.cloud.google.com/dialogflow/cx/docs/concept/fulfillment#text),
[custom payloads](https://docs.cloud.google.com/dialogflow/cx/docs/concept/fulfillment#payload),
and
[conditional responses](https://docs.cloud.google.com/dialogflow/cx/docs/concept/fulfillment#cond)),
[parameter presets](https://docs.cloud.google.com/dialogflow/cx/docs/concept/fulfillment#param-preset),
and
[webhook header values](https://docs.cloud.google.com/dialogflow/cx/docs/concept/webhook#auth)
to
generate dynamic values during conversations.

## Function syntax

All system functions follow the pattern of
`$sys.func.<FUNCTION NAME>(<ARGUMENT 1>, <ARGUMENT 2>, ...)`.
For example,
`$sys.func.RAND()`, `$sys.func.ADD(1,2)`.

The names of the functions are all capitalized
(except the random number generation function,
which you can use with both `RAND` and the legacy name `rand`).

The arguments of the functions can be:

- inline values (such as number `1`, string `"abc"`, boolean `true`, and list `[1, 2, 3]`)
- references to parameters (such as `$session.params.a`, check
  [parameters guide](https://docs.cloud.google.com/dialogflow/cx/docs/concept/parameter)
  for more details about the syntax of referencing parameters)

  > [!NOTE]
  > **Note:** If the parameter referenced by the function expression is not set, it is treated as `null`.

  > [!NOTE]
  > **Note:** Inline object (such as `{"field" : "value"}`) is not supported. Consider referencing the object through parameters.

- nested functions (such as `$sys.func.ADD($sys.func.MINUS(2, 1), 3)`)

## Check results of system functions

During the conversation,
if Dialogflow evaluates any inline system function expressions
to generate dynamic values,
you can find the results of the evaluations in the
[QueryResult](https://docs.cloud.google.com/dialogflow/cx/docs/reference/rest/v3/QueryResult).

Specifically, there is a key called `SystemFunctionResults`
in the `DiagnosticInfo` struct field, which logs the results (and errors)
of system function evaluations.

## Functions

Below are the system functions that Dialogflow currently supports.

### ADD

You can use the `ADD` function to add multiple numbers together.

The function takes an arbitrary number of arguments.
All arguments must be numbers.

For example, the following expression produces a value of `3`.

```
$sys.func.ADD(1, 2)
```

<br />

### ADD_DATE

You can use the `ADD_DATE` function to do arithmetic operations on dates.

The function takes the following arguments:

- the datetime object that you want to change
- the value you want to add (if positive) or subtract (if negative)
- the unit of time - string specifying the unit (days/months/hours/minutes) that you want to add/subract.

The list of supported units of time:

- "YEARS"
- "MONTHS"
- "DAYS"
- "WEEKS"
- "HOURS"
- "MINUTES"
- "SECONDS"

For example, the datetime struct representing `8/9/2021 15:23:10` may look like:

```
    {
        "year" : 2021
        "month" : 8,
        "day" : 9,
        "hours": 15,
        "minutes" : 23,
        "seconds" : 10,
        "nanos" : 0
    }
```

<br />

If it's stored in `$session.params.time` the ADD_DATE invocation will produce
datetime objects like in the table below:

| Expression | Result (datetime object) |
|---|---|
| `$sys.func.ADD_DATE($session.params.time, 5, "DAYS")` | `8/14/2021 15:23:10` |
| `$sys.func.ADD_DATE($session.params.time, -9, "MONTHS")` | `11/9/2020 15:23:10` |
| `$sys.func.ADD_DATE($session.params.time, 38, "MINUTES")` | `8/9/2021 16:01:10` |

Note that the results are shown as a datetime string for convenience, but they
are actually datetime objects, and you can use them with other functions like
`$sys.func.FORMAT_DATE` or `$sys.func.GET_FIELD`:

| Expression | Result |
|---|---|
| `$sys.func.GET_FIELD($sys.func.ADD_DATE($session.params.time, 5, "DAYS"), "day")` | `14` |
| `$sys.func.FORMAT_DATE($sys.func.ADD_DATE($session.params.time, -9, "MONTHS"), "yy MMM dd")` | `20 Nov 09` |

### APPEND

You can use the `APPEND` function to append value(s) to the end of a list.

The function takes the following arguments:

- the list to append values.

  > [!NOTE]
  > **Note:** If the list is `null`, the function treats it as an empty list.

- an arbitrary number of values to be appended to the end of the list.

  If the value is a list, the values inside the list will be appended one by one.

For example:

| Expression | Result |
|---|---|
| `$sys.func.APPEND([1, 2, 3], 4)` | `[1, 2, 3, 4]` |
| `$sys.func.APPEND(["a", "b", "c"], "d", ["e", "f"])` | `["a", "b", "c", "d", "e", "f"]` |
| `$sys.func.APPEND(null, 1, 2, [3, 4])` | `[1, 2, 3, 4]` |

### CONCATENATE

You can use the `CONCATENATE` function to concatenate strings together.

The function takes an arbitrary number of arguments.
All arguments must be strings. Use the [TO_TEXT function](https://docs.cloud.google.com/dialogflow/cx/docs/reference/system-functions#func-totext) to
convert values of other types (such as number, object, list) to a string.

For example, the following expression produces a value of `"$100"`.

```
$sys.func.CONCATENATE("$", "100")
```

<br />

### CONTAIN

You can use the `CONTAIN` function to
check if a list contains a certain element.

The function takes two arguments:

- the specified list

  > [!NOTE]
  > **Note:** If the list is `null`, the function produces a value of `false`.

- the value for the existence check

For example, the following expression produces a value of `true`.

```
$sys.func.CONTAIN([1, 2, 3], 1)
```

<br />

### COUNT

You can use the `COUNT` function to get the number of elements in a list.

The function takes one argument:

- the list to count

  > [!NOTE]
  > **Note:** If the list is `null`, the function produces a value of `0`.

For example, the following expression produces a value of `3`.

```
$sys.func.COUNT([1, 2, 3])
```

<br />

### DIVIDE

You can use the `DIVIDE` function to calculate the quotient of two parameters.

The function takes three arguments:

- the dividend
- the divisor

  > [!NOTE]
  > **Note:** Dividing by zero causes an error. The expression is not evaluated and the error message is added to `DiagnosticInfo`.

- scale - the number of decimal places in the quotient, optional, 3 by default

Examples:

| Expression | Result |
|---|---|
| `$sys.func.DIVIDE(10, 2)` | `5.000` |
| `$sys.func.DIVIDE(10, -2)` | `-5.000` |
| `$sys.func.DIVIDE(10, 3, 0)` | `3` |
| `$sys.func.DIVIDE(10.57, 3, 4)` | `3.5233` |

### FILTER

You can use the `FILTER` function to filter or extract values from list and
composite parameters using syntax from the [JsonPath library](https://github.com/json-path/JsonPath).

The function takes two arguments:

- the parameter reference in quotes for the [list or composite parameter](https://docs.cloud.google.com/dialogflow/cx/docs/concept/parameter#types) to be filtered.
- a JsonPath expression represented as a string.

You can write an expression that parses values from a list or composite
parameter, and this expression can be a path to a nested object that also
includes a logical expression for filtering. See
[JsonPath's documentation](https://github.com/json-path/JsonPath) for more
information on writing JsonPath expressions.

Dialogflow may not support all of the JsonPath operators or functions. See below
for examples of operators and expressions that are fully supported.

Consider the following list parameter `$session.params.shapes`:

```
    {
      "result": {
        "shapes": [
          {
            "id": 1,
            "shape": "circle",
            "colors": ["red","blue"]
          },
          {
            "id": 2,
            "shape": "square",
            "colors": ["green","orange"]
          },
          {
            "id": 3,
            "colors": "blue"
          }
        ]
      }
    }
```

Here are examples of extracting elements from the parameter above.

| Expression | Result |
|---|---|
| `$sys.func.FILTER("$session.params.shapes", "$.result.shapes[:1]")` | \[ { "id": 1, "shape": "circle", "colors": \[ "red", "blue" \] } \] |
| `$sys.func.FILTER("$session.params.shapes", "$.result.shapes[?(@.colors == 'blue')]")` | \[ { "id": 3, "colors": "blue" } \] |
| `$sys.func.FILTER("$session.params.shapes", "$.result.shapes[?(@.id < 3 && @.shape != 'square')].colors")` | \[ \[ "red", "blue" \] \] |
| `$sys.func.FILTER("$session.params.shapes", "$.result.shapes[?(@.id > 1 || @.shape == 'circle')].colors")` | \[ \[ "red", "blue" \], \[ "green", "orange" \], "blue" \] |
| `$sys.func.FILTER("$session.params.shapes", "$.result.shapes[*].shape")` | \[ "circle", "square" \] |

### FORMAT_DATE

You can use the `FORMAT_DATE` function to
represent a date / time using a specified format.

The function takes the following arguments:

- the time that you want to format
- the chosen format represented as a string (case sensitive)
- (optional) the desired [language tag](https://docs.cloud.google.com/dialogflow/cx/docs/reference/language#table) for the output represented as a string

The time (first argument) that you want to format should
either be of a time-related
[entity type](https://docs.cloud.google.com/dialogflow/cx/docs/reference/system-entities)
(such as @sys.date, @sys.time, and @sys.date-time)
or an object with some or all of the following fields:

- year
- month
- day
- hours
- minutes
- seconds
- nanos

For example, the object may look like this:

```
    {
        "day" : 9,
        "hours": 15,
        "minutes" : 23,
        "month" : 8,
        "nanos" : 0,
        "seconds" : 10,
        "year" : 2021
    }
```

The format (second argument) is case sensitive and should be a string
consisting of symbols with the following meanings:

| Symbol | Meaning | Examples |
|---|---|---|
| y | Year | 2021; 21 |
| M | Month of year | 06; 6; Jun; June |
| d | Day of month | 10 |
| E | Day of week | Tuesday; Tue; T |
| a | AM/PM of day | PM |
| H | Hour in day (0-23) | 0 |
| h | Clock hour (1-12) | 12 |
| m | Minute of hour | 30 |
| s | Secound of minute | 59 |
| S | Millisecond | 978 |
| z | Time-zone name | Pacific Standard Time; PST |

The language (third argument) should be a
[tag](https://docs.cloud.google.com/dialogflow/cx/docs/reference/language#table) such as `en` or `fr-CA`.

The language tag is optional, and if it is unspecified,
the output is in English by default,
which means the two expressions below are equivalent:

```
$sys.func.FORMAT_DATE(<time>, <format>)
$sys.func.FORMAT_DATE(<time>, <format>, "en")
```
If the language tag is invalid, the output is also in English.

<br />

For example, if
[session parameter](https://docs.cloud.google.com/dialogflow/cx/docs/concept/parameter#session)
`time` is an object representing 8:30AM PST on 2021/06/30,
you can generate the following strings representing the time
using the `FORMAT_DATE` function:

```
$sys.func.FORMAT_DATE($session.params.time, <format>, "en")
```

<br />

| Formats | Outputs |
|---|---|
| "dd/MM/yy" | "30/06/21" |
| "dd MMM yyyy" | "30 Jun 2021" |
| "yyyy-MM-dd" | "2021-06-30" |
| "EEEE, MMMM dd" | "Wednesday, June 30" |
| "MM-dd h:mm a" | "06-30 8:30 AM" |
| "hh:mm:ss a, zzzz" | "08:30:00 AM, Pacific Standard Time" |
| "hh:mm:ss.SSS" | "08:30:00.000" |

### GET

You can use the `GET` function to get the value from a list based on an index.

The function takes the following arguments:

- the list to get values

- the index (0-indexed) of the desired value

For example:

| Expression | Result |
|---|---|
| `$sys.func.GET([1, 2, 3], 0)` | `1` |
| `$sys.func.GET(["a", "b", "c"], 2)` | `"c"` |

If the index specified does not exist within the list, the `GET` function will
return a string containing the full text of the function. When this occurs, the
interaction log for this transaction will contain a
[QueryResult](https://docs.cloud.google.com/dialogflow/cx/docs/reference/rest/v3/QueryResult) with a
`SystemFunctionResults` and `DiagnosticInfo` section that states "Index is out
of bound."

For example:

| Expression | Result |
|---|---|
| `$sys.func.GET([1, 2, 3], 8)` | `"$sys.func.GET([1, 2, 3], 8)"` |

This expected behavior can cause runtime issues if the error isn't caught and
handled gracefully. This is typically handled by using an
[IF function](https://docs.cloud.google.com/dialogflow/cx/docs/reference/system-functions#func-if) to test the validity of the index before issuing the
`GET` function, however this is complicated by the fact that a runtime error
in any part of an `IF` function will render the entire `IF` function to
error. One way to gracefully test for this condition during runtime is to first
use a [parameter preset](https://docs.cloud.google.com/dialogflow/cx/docs/concept/fulfillment#param-preset)
to assign the `GET` function to a parameter and then reference the value of that
parameter as one of your `IF` clauses.

For example:

- Parameter preset:

  | Parameter | Value | Result |
  |---|---|---|
  | `__value_a` | `$sys.func.GET([1, 2, 3], 1)` | `2` |
  | `__value_b` | `$sys.func.GET([1, 2, 3], 8)` | `"$sys.func.GET([1, 2, 3], 8)"` |

- `IF` evaluation:

  | Expression | Result |
  |---|---|
  | `$sys.func.IF($sys.func.CONTAIN([1, 2, 3], 1), $session.params.__value_a, 0)` | `2` |
  | `$sys.func.IF($sys.func.CONTAIN([1, 2, 3], 8), $session.params.__value_b, 0)` | `0` |

### GET_FIELD

You can use the `GET_FIELD` function to get a value from an object using a key.

The function takes the following arguments:

- the object

- the key of the desired value

For example, if an object `$session.params.apple` is:

    {
      "name" : "apple",
      "color": "red",
    }

| Expression | Result |
|---|---|
| `$sys.func.GET_FIELD($session.params.apple, "name")` | `"apple"` |
| `$sys.func.GET_FIELD($session.params.apple, "color")` | `"red"` |

### IDENTITY

The `IDENTITY` function returns the input argument without
any implicit type conversion, which may happen with raw parameter references.

The function takes one argument:

- the value to return

This function is useful for retaining the value type when you reference
parameters in the [parameter presets](https://docs.cloud.google.com/dialogflow/cx/docs/concept/fulfillment#param-preset)
**Value** field.

One example is when you want to reference a parameter that returns a number
in the parameter presets **Value** field
and assign this value to a new parameter.
To make sure that the new parameter value type is number,
set the parameter preset value to
`$sys.func.IDENTITY($session.params.amount)`, where `amount` is
the original parameter name.

The following parameter preset configuration sets the new
`assigned-amount` parameter to be the same number value as
the `amount` parameter at runtime:

| Parameter | Value |
|---|---|
| assigned-amount | $sys.func.IDENTITY($session.params.amount) |

Another example is when you want to pass a composite object
parameter value to a new parameter through
parameter presets.

When referencing a composite object parameter
that has a field named `original`
(for example,
an [intent parameter](https://docs.cloud.google.com/dialogflow/cx/docs/concept/parameter#intent-ref)
that matches an entity at runtime,
in which the `original` field
captures the value written or spoken by the end-user),
the default behavior is to
return a scalar string that is present in the `original` field.

For instance, if an object `currency-object` representing the
[@sys.unit-currency](https://docs.cloud.google.com/dialogflow/cx/docs/reference/system-entities#desc)
system entity is:

```
    {
        "original" : "$400",
        "amount": 400,
        "currency": "USD"
    }
```

The following parameter preset
configuration will set `new-currency-object` to be "$400" at runtime:

| Parameter | Value |
|---|---|
| new-currency-object | $session.params.currency-object |

In some cases, you need the full composite object,
rather than the scalar representation,
and you can then use the `IDENTITY` function to help pass the full object.

For example, the following parameter preset configuration will set
`new-currency-object` to be the same object as `currency-object` at runtime,
which contains fields `original`, `amount`, and `currency`:

| Parameter | Value |
|---|---|
| new-currency-object | $sys.func.IDENTITY($session.params.currency-object) |

### IF

> [!NOTE]
> **Note:** Always wrap the logical condition (first argument) in double quotation marks for best practices.

You can use the `IF` function to
return one of the two values based on a logical condition.

The function takes three arguments:

- the logical expression (whose syntax is the same as the syntax of [condition](https://docs.cloud.google.com/dialogflow/cx/docs/reference/condition))
- the value to return if the expression is true
- the value to return if the expression is false

For example, the following expression produces a value of `1`.

```
$sys.func.IF("1 < 2", 1, 2)
```

<br />

### IS_CREDIT_CARD_NUMBER

Performs a Luhn algorithm check to determine whether the candidate number is a valid card number. Null or empty strings are not valid credit card numbers.

The function takes one argument:

- the credit card number represented as a string

The function returns `true` if the credit card number provided is valid and `false` otherwise. For example, `true` is returned by the function below when provided a Visa test number.

```
$sys.func.IS_CREDIT_CARD_NUMBER("4111111111111111")
```

### IS_DATE

Validates if a date can be parsed given a date string, date format, and an optional language code. This is for dates that do not reference a time-zone.

The function takes three arguments:

- date string
- date format pattern represented as a string ([patterns for formatting and parsing](https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html#patterns))
- language code represented as a string (optional, defaulting to English) ([supports IETF BCP 47 language tags](https://en.wikipedia.org/wiki/IETF_language_tag#List_of_common_primary_language_subtags) and legacy tags in the [IANA Language Subtag Registry](https://www.iana.org/assignments/language-subtag-registry/language-subtag-registry))

The function returns `true` if the date provided is valid and `false` otherwise. The function will ensure that the day-of-month is valid for the year-month, rejecting invalid values including days that only fall on leap years.

| Expression | Result |
|---|---|
| `$sys.func.IS_DATE("2021-04-29", "uuuu-MM-dd")` | `true` |
| `$sys.func.IS_DATE("21 Apr 29", "uu MMM dd")` | `true` |
| `$sys.func.IS_DATE("21 四月 29", "uu MMM dd", "zh-cn")` | `true` |
| `$sys.func.IS_DATE("21 апр 29", "uu MMM dd", "ru")` | `true` |
| `$sys.func.IS_DATE("21 Apr 42", "uu MMM dd")` | `false` |
| `$sys.func.IS_DATE("21 Feb 29", "uu MMM dd")` | `false` |

> [!NOTE]
> **Note:** It is important to use "uuuu-MM-dd" over "yyyy-MM-dd" for a date like "2021-04-29". Year is represented by "u" in the pattern and "y" represents year-of-era.

### IS_FUTURE_DATE

A function to check if the provided date or datetime is after the current datetime. Both the argument and the current time use the timezone provided in the conversation request. If the timezone is not present in the conversation request, the timezone defined in the agent settings will be used.

The function takes one argument:

- the date or datetime object

The date or datetime object should
either be of a date or datetime-related
[entity type](https://docs.cloud.google.com/dialogflow/cx/docs/reference/system-entities)
(such as @sys.date, and @sys.date-time)
or an object with some or all of the following fields:

- year
- month
- day
- hours
- minutes
- seconds
- nanos

For example, the object may look like this:

```
    {
        "day" : 16,
        "month" : 5,
        "year" : 2123
    }
```

> [!NOTE]
> **Note:** A valid date must be provided. For example, May 33, 2023, will return an error. If hour and minute are included, the comparison will be made using date and time, and the second and nano parts will default to 0 if missing. If provided the current date with the hour or minute parts excluded, the function will return `false`.

For example, if `$session.params.your-date` = `{"year": 2123, "month": 5, "day": 16}`, then the following returns `true`.

```
$sys.func.IS_FUTURE_DATE($session.params.your-date)
```

### IS_PAST_DATE

A function to check if the provided date or datetime is before the current datetime. Both the argument and the current time use the timezone provided in the conversation request. If the timezone is not present in the conversation request, the timezone defined in the agent settings will be used. A valid date must be provided. For example, May 33, 2023, would return an error.

The function takes one argument:

- the date or datetime object

The date or datetime object should
either be of a date or datetime-related
[entity type](https://docs.cloud.google.com/dialogflow/cx/docs/reference/system-entities)
(such as @sys.date, and @sys.date-time)
or an object with some or all of the following fields:

- year
- month
- day
- hours
- minutes
- seconds
- nanos

For example, the object may look like this:

```
    {
        "day" : 16,
        "month" : 5,
        "year" : 1989
    }
```

> [!NOTE]
> **Note:** A valid date must be provided. For example, May 33, 2023, will return an error. If hour and minute are included, the comparison will be made using date and time, and the second and nano parts will default to 0 if missing. If provided the current date with the hour or minute parts excluded, the function will return `false`.

For example, if `$session.params.your-date` = `{"year": 1989, "month": 5, "day": 16}`, then the following returns `true`.

```
$sys.func.IS_PAST_DATE($session.params.your-date)
```

### IS_PHONE_NUMBER

Tests whether a phone number can be parsed into a valid number for the given region. Note this doesn't verify the number is actually in use, which is impossible to tell by just looking at a number itself.

The function takes two arguments:

- a phone number represented as a string
- a region code represented as a string (optional)

The function returns `true` if the phone number provided is valid and `false` otherwise. For example, if the number is in an international format, prefixed with "+1" for the US and Canada, then Region Code can be excluded. Will default to US region if the number is not prefixed with "+" and the Region Code is not set. [Click here](https://docs.oracle.com/cd/E13214_01/wli/docs92/xref/xqisocodes.html) for a list of valid ISO-3166 Country Codes.

| Expression | Result |
|---|---|
| `$sys.func.IS_PHONE_NUMBER("650-206-5555", "US")` | `true` |
| `$sys.func.IS_PHONE_NUMBER("+16502065555")` | `true` |
| `$sys.func.IS_PHONE_NUMBER("2065555")` | `false` |

### JOIN

You can use the `JOIN` function to
concatenate the elements of a list using a specified delimiter.

If the elements in the list are not strings,
the result of the function is equivalent to
applying the [TO_TEXT](https://docs.cloud.google.com/dialogflow/cx/docs/reference/system-functions#func-totext) function to each element before joining.

The function takes the following arguments:

- the delimiter
- the list to join
- (optional) the final delimiter

For example:

| Expression | Result |
|---|---|
| `$sys.func.JOIN(", ", ["a", "b", "c"])` | `"a, b, c"` |
| `$sys.func.JOIN(", ", ["a", "b", "c"], ", and ")` | `"a, b, and c"` |

### LEN

You can use the `LEN` function to
get the length (number of characters) of a string. Use the [TO_TEXT function](https://docs.cloud.google.com/dialogflow/cx/docs/reference/system-functions#func-totext)
to convert values of other types (such as number, object, list) to a string.

The function takes one argument:

- the specified string

For example, the following expression produces a value of `6`.

```
$sys.func.LEN("google")
```

<br />

### LOWER

You can use the `LOWER` function to turn a string to lowercase. Use the
[TO_TEXT function](https://docs.cloud.google.com/dialogflow/cx/docs/reference/system-functions#func-totext) to convert values of other types
(such as number, object, list) to a string.

The function takes one argument:

- the string to convert to lowercase

For example, the following expression produces a value of `"abc"`.

```
$sys.func.LOWER("ABC")
```

<br />

### MATCH

You can use the `MATCH` function to
find the index of an element in a list.
If a match is found,
the index of the first match in the list is returned.
If a match is not found,
`-1` is returned.

The function takes two arguments:

- the list to search
- the element to find

For example, the following expression produces a value of `0`.

```
$sys.func.MATCH([1, 2, 3], 1)
```

<br />

### MID

You can use the `MID` function to get a segment of a string. Use the
[TO_TEXT function](https://docs.cloud.google.com/dialogflow/cx/docs/reference/system-functions#func-totext) to convert values of other types
(such as number, object, list) to a string.

The function takes three arguments:

- the string to extract a segment from
- the starting position of the segment (1-indexed)
- the length (number of characters) of the segment

For example, the following expression produces a value of `"gl"`.

```
$sys.func.MID("google", 4, 2)
```

<br />

### MINUS

You can use the `MINUS` function to subtract one number from another.

The function takes two arguments:

- the minuend (number to be subtracted from)
- the subtrahend (number to subtract)

For example, the following expression produces a value of `1`.

```
$sys.func.MINUS(3, 2)
```

<br />

### MULTIPLY

You can use the `MULTIPLY` function to calculate the product of an arbitrary number of provided parameters.

The function takes two or more arguments:

- the factor 1
- the factor 2
- the factor 3 (optional)
- ...

Examples:

| Expression | Result |
|---|---|
| `$sys.func.MULTIPLY(2, 3)` | `6` |
| `$sys.func.MULTIPLY(2, -4)` | `-8` |
| `$sys.func.MULTIPLY(2.5, 4, 5)` | `50` |
| `$sys.func.MULTIPLY(2.5, 4, 5, 2, -2)` | `-200` |

### NESTED_FIELD

A function to retrieve a nested value from a composite object or a list within a composite object.

The function takes at least two arguments:

- the name in quotes of the [composite parameter](https://cloud.google.com/dialogflow/cx/docs/concept/parameter#types) which contains the nested value
- one or more keys represented as strings that reference the path to the nested value

For example, if parameter `$session.params.your-param-1` = `{"a": {"b": "Value"}}`

| Expression | Result |
|---|---|
| `$sys.func.NESTED_FIELD("$session.params.your-param-1", "a", "b")` | `"Value"` |

> [!NOTE]
> **Note:** More than ten levels of nesting is not supported.

This function can be used in the Parameter Preset Form to update a nested value within a composite object or add a new key to a composite object.

For example, if parameter `$session.params.your-param-2` = `{"a": {"b": 2, "c": [1, 2, 3]}}`, you can do the following:

- Update an existing key

  | Parameter | Value |
  |---|---|
  | `$sys.func.NESTED_FIELD("$session.params.your-param-2", "a", "b")` | `3` |

  The updated parameter becomes `{"a": {"b": 3, "c": [1, 2, 3]}}`.
- Add a new key

  | Parameter | Value |
  |---|---|
  | `$sys.func.NESTED_FIELD("$session.params.your-param-2", "a", "d")` | `"new"` |

  The updated parameter becomes `{"a": {"b": 3, "c": [1, 2, 3], "d": "new"}}`.
- Update a list value

  | Parameter | Value |
  |---|---|
  | `$sys.func.NESTED_FIELD("$session.params.your-param-2", "a", "c[0]")` | `4` |

  The updated parameter becomes `{"a": {"b": 3, "c": [4, 2, 3]}}`.

### NOW

You can use the `NOW` function to get the current time.

The function takes no arguments.

For example, the following expression produces an object of
[@sys.date-time](https://docs.cloud.google.com/dialogflow/cx/docs/reference/system-entities) entity type
representing the current time. The current time uses the timezone provided in
the conversation request. If the timezone is not present in the conversation
request, the timezone defined in the agent settings will be used.

```
$sys.func.NOW()
```

<br />

### RAND

> [!NOTE]
> **Note:** The previous name `rand` remains valid to use.

The function takes no arguments.

You can use the `RAND` function to generate a random floating point number
in the range \[0,1), such as in the expression below.

```
$sys.func.RAND()
```

<br />

### REMOVE

You can use the `REMOVE` function to remove value(s) from a list.

The function takes the following arguments:

- the list to remove values.

  > [!NOTE]
  > **Note:** If the list is `null`, the function produces a value of `null`.

- an arbitrary number of values to be removed from the list.

  If the value is a list, the values inside the list will be removed one by one.

  All occurrences of the values will be removed from the list.

For example:

| Expression | Result |
|---|---|
| `$sys.func.REMOVE([1, 2, 3, 2, 1], 2)` | `[1, 3, 1]` |
| `$sys.func.REMOVE([1, 2, 3], 4)` | `[1, 2, 3, 4]` |
| `$sys.func.REMOVE(["a", "b", "c", "a", "d"], "a", ["b", "c"])` | `["d"]` |
| `$sys.func.REMOVE(null, 1, 2)` | `null` |

### ROUND

You can use the `ROUND` function to round a decimal number to a specified number of decimal places.

The function takes 2 arguments:

- the decimal number to round.
- optional number of decimal places. If not specified, the decimal number is rounded to integer.

For example:

| Expression | Result |
|---|---|
| `$sys.func.ROUND(10.49)` | `10` |
| `$sys.func.ROUND(10.50)` | `10` |
| `$sys.func.ROUND(10.51)` | `11` |
| `$sys.func.ROUND(10.49, 1)` | `10.5` |
| `$sys.func.ROUND(10.43, 1)` | `10.4` |
| `$sys.func.ROUND(-10.123, 2)` | `-10.12` |
| `$sys.func.ROUND(-10.127, 2)` | `-10.13` |

> [!NOTE]
> **Note:** you must use "." as a decimal separator.

### SPLIT

You can use the `SPLIT` function to
divide text around a specified character or string
and puts the fragments into a list. Use the [TO_TEXT function](https://docs.cloud.google.com/dialogflow/cx/docs/reference/system-functions#func-totext)
to convert values of other types (such as number, object, list) to a string.

The function takes two arguments:

- the string to split.
- a regular expression that represents the delimiter.

For example, the following expressions both produce a value of `["a", "b", "c"]`.

```
$sys.func.SPLIT("a/b/c", "/")
$sys.func.SPLIT("a.b.c", "\.")
```

<br />

To access an element from the returned list, use the [GET function](https://docs.cloud.google.com/dialogflow/cx/docs/reference/system-functions#func-get).

An example of an expression that produces a value of `["a", "b", "c"]` and
isolates the first element would be:

```
$sys.func.GET($sys.func.SPLIT("a.b.c", "\."),0)
```

<br />

If the delimiter does not appear within the string being split, calling $sys.func.SPLIT() will result in a list that contains the original string to split as its only entry.

For example, the following expression produces a value of `["a/b/c"]`.

```
$sys.func.SPLIT("a/b/c", "-")
```

<br />

### SUBSTITUTE

You can use the `SUBSTITUTE` function to
replace existing text with new text in a string. Use the [TO_TEXT function](https://docs.cloud.google.com/dialogflow/cx/docs/reference/system-functions#func-totext)
to convert values of other types (such as number, object, list) to a string.

The function takes three arguments:

- the original string
- a regular expression whose matches are replaced
- the text for replacement

For example, the following expressions both produce a value of `"google"`.

```
$sys.func.SUBSTITUTE("good", "d", "gle")
$sys.func.SUBSTITUTE("goo gl e", "\s+", "")
```

<br />

### TO_TEXT

You can use the `TO_TEXT` function to
convert a value of other types (such as a number or a list) to a string.

The function takes one argument:

- the original value to turn into a string form, which can be of any type (e.g. number, list, object)

For example, the following expression produces a value of `"3"`.

```
$sys.func.TO_TEXT(3)
```

<br />

### TO_NUMBER

You can use the `TO_NUMBER` function to
convert a value of other types (such as a string or a boolean) to a number.

The function takes one argument:

- the original value to turn into a number form, which can be type of string, boolean or number.

For example, the following expression produces a value of `-3`.

```
$sys.func.TO_NUMBER("-3")
```

<br />

### TO_OBJECT

You can use the `TO_OBJECT` function to convert an arbitrary JSON string to an object.

The function takes one argument:

- The json string representing json object or array. The values in the json can be valid json identifier (numbers, strings, arrays, booleans, objects), or session parameters and function calls.

For example:

    $sys.func.TO_OBJECT("{ 'name': '$session.params.username', 'number': 20.48, 'calculation': '$sys.func.ADD($session.params.five, 2.4)', 'inner_object': { 'array': [1, 2, '$session.params.three'] } }")

will produce the following object

```
{
  name: "User Name",
  number: 20.48,
  calculation: 7.4,
  inner_object: {
    array: [1, 2, 3]
  }
}
```

You can apply the [`$sys.func.GET_FIELD`](https://docs.cloud.google.com/dialogflow/cx/docs/reference/system-functions#func-getfield) function to extract a
necessary field from this object.

    $sys.func.TO_OBJECT("[{ 'name': 'Charlie', 'age': 20 }, { 'name': 'Alpha', 'age': 30 }]" }]")

```
[{
  name: 'Charlie',
  age: 20
}, {
  name: 'Alpha',
  age: 30
}]
```

You can apply the [`$sys.func.GET`](https://docs.cloud.google.com/dialogflow/cx/docs/reference/system-functions#func-get) function to extract a necessary
element from this list.

### TO_PHONE_NUMBER

Extract the country code, national destination code, and number from a string phone number.

The function takes two arguments:

- a phone number represented as a string
- a region code represented as a string (optional)

The function returns an object containing the country code, area code, and number. For example, if the number is in an international format, prefixed with "+1" for the US and Canada, then Region Code can be excluded. Will default to US region if the number is not prefixed with "+" and the region code is not set. [Click here](https://docs.oracle.com/cd/E13214_01/wli/docs92/xref/xqisocodes.html) for a list of valid ISO-3166 Country Codes.

| Expression | Result |
|---|---|
| `$sys.func.TO_PHONE_NUMBER("650-206-5555", "US")` | `{"country-code":"1", "area-code":"650", "number":"2065555"}` |
| `$sys.func.TO_PHONE_NUMBER("+491771783584")` | `{"country-code":"49", "area-code":"177", "number":"1783584"}` |
| `$sys.func.TO_PHONE_NUMBER("2065555")` | `{}` |

### UNIQUE

You can use the `UNIQUE` function to
remove duplicates from a list and return a list with distinct elements.
The following rules apply:

- The result is deterministic: if there are duplicates in the input list,
  the first appearance of the element always remains in the list.

- Any input element types, including struct and list, are allowed.

- Null element is ignored and will NOT appear in the result list.

The function takes the following arguments:

- the list to remove duplicates from.

For example:

| Expression | Result |
|---|---|
| `$sys.func.UNIQUE([1, 2, 3])` | `[1, 2, 3]` |
| `$sys.func.UNIQUE(["a", "c", "b", "c"])` | `["a", "c", "b"]` |
| `$sys.func.UNIQUE([[3, 2], [3, 2], [3, 1]])` | `[[3, 2], [3, 1]]` |
| `$sys.func.UNIQUE([null, "abc", true, 1.0])` | `["abc", true, 1.0]` |

### UPPER

You can use the `UPPER` function to turn a string to uppercase. Use the
[TO_TEXT function](https://docs.cloud.google.com/dialogflow/cx/docs/reference/system-functions#func-totext) to convert values of other types
(such as number, object, list) to a string.

The function takes one argument:

- the string to convert to uppercase

For example, the following expression produces a value of `"ABC"`.

```
$sys.func.UPPER("abc")
```

<br />

### URL_ENCODE

You can use the `URL_ENCODE` function to URL encode a string. This is useful
when calling a webhook with a session parameter that may include specific
characters that need to be URL encoded.

The function takes one argument:

- the string to URL encode.

For example, the following expression produces a value of `abc%2B%2F%3D`.

```
$sys.func.URL_ENCODE("abc+/=")
```

<br />

### UUID

The function takes no arguments.

You can use the `UUID` function to generate a universal unique identifier
in the format `^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$`.

```
$sys.func.UUID()
```

<br />