# Functions
> Decide what happens when visitors use a Widget: API calls, messages, links, uploads and data updates.
Functions are the behavior behind a Widget's buttons, forms and fields. You attach a function to an element by its **Function name**, and the function's **Function type** decides what happens when a visitor uses that element.
Manage functions in the builder's **Functions** tab.

```jsx
```
Click a function to open it, and **Add function** to create one.


> [!NOTE]
>
> While a function is missing required settings, such as a URL, the builder shows **Not saved: Function has incomplete fields** and doesn't save your changes. Finish or delete the function to save again.
## Function Types
Each type does a different job. Pick the one that matches what the element should do.

> [accordion] Call API
>
> Sends a request to an API endpoint and uses the response. The request runs on QwryAI's servers, so visitors never see its settings.
>
> | Setting | Description |
> | :- | :- |
> | **URL** | The endpoint to call. Supports [template tokens](#template-tokens). |
> | **Method** | `GET`, `POST`, `PUT`, `PATCH` or `DELETE`. |
> | **Headers** | Key-value pairs sent as request headers. Supports [template tokens](#template-tokens). |
> | **Parameters** | Query parameters added to the URL. Supports [template tokens](#template-tokens). |
> | **Body** | The request body. Supports [template tokens](#template-tokens). |
> | **Return schema** | Response fields to save into Widget variables, each with a type (**Text**, **Number**, **Boolean**, **Date** or **Object**) and an **Array** option. **Populate from API** calls your endpoint and fills these in from its response. |
> | **On start** | [Follow-up](#after-a-function-runs) that runs before the request is sent. |
> | **On success** | [Follow-up](#after-a-function-runs) when the request succeeds. |
> | **On failure** | [Follow-up](#after-a-function-runs) when the request fails. |
> | **Additional inputs** | Values passed in where the function is used. See [Additional Inputs](#additional-inputs). |
> [accordion] Upload file
>
> Uploads files from the visitor's browser straight to your endpoint, one request per file. QwryAI doesn't store the files. Attach it to a `Button` to open the visitor's file picker. See [File Uploads](/docs/developer-guides/widgets/file-uploads) for the endpoint contract.
>
> | Setting | Description |
> | :- | :- |
> | **Endpoint** | Your upload URL and method, `POST` or `PUT`. It must start with `https://`. Supports [template tokens](#template-tokens). |
> | **File field** | The multipart field the file is sent under. Default `file`. |
> | **Target field** | The Widget variable that stores the uploaded file's URL. |
> | **Accepted types** | Comma-separated extensions or MIME types, for example `.pdf, image/*`. Empty accepts any type. |
> | **URL field** | Path in your JSON response that holds the file's URL, for example `data.url`. |
> | **Max size (MB)** | Size limit per file, up to 30 MB. |
> | **Allow multiple** | Lets the visitor pick more than one file. |
> | **Max files** | How many files they can pick, up to 5. Shown when **Allow multiple** is on. |
> | **Headers** | Request headers. They're sent from the visitor's browser, so visitors can see them. `Content-Type` isn't allowed. |
> | **Query params** | Query parameters added to the URL. Supports [template tokens](#template-tokens). |
> | **Form fields** | Extra multipart fields sent with every file. Supports [template tokens](#template-tokens). |
> | **Return schema** | Response fields to save into Widget variables. |
> | **On start** | [Follow-up](#after-a-function-runs) that runs once, before the first file is sent. |
> | **On success (per file)** | [Follow-up](#after-a-function-runs) that runs for each uploaded file. |
> | **On failure (per file)** | [Follow-up](#after-a-function-runs) that runs for each file that failed. |
> | **Additional inputs** | Values passed in where the function is used. See [Additional Inputs](#additional-inputs). |
>
> Besides the Widget's variables, the endpoint, query parameters and form fields can use `{{conversationId}}`, `{{chatbotId}}` and `{{widgetId}}`.
> [accordion] Run client-side code
>
> Runs a function on your own website, in the visitor's browser. Use it to reach your page's own data or code, such as a cart.
>
> | Setting | Description |
> | :- | :- |
> | **Wait for response** | Waits for your function's result, for up to 60 seconds. |
> | **Inputs** | Key-value pairs passed to your function. Supports [template tokens](#template-tokens). |
> | **Return schema** | Fields from your function's `data` to save into Widget variables. |
> | **On start** | [Follow-up](#after-a-function-runs) that runs before your function is called. |
> | **On success** | [Follow-up](#after-a-function-runs) when your function succeeds. |
> | **On failure** | [Follow-up](#after-a-function-runs) when it fails or times out. |
> | **Additional inputs** | Values passed in where the function is used. They're passed to your function along with **Inputs**. |
>
> **Handling the function on your page**
>
> Register a handler on your website with `registerTools`, the same call used for [client-side Actions](/docs/developer-guides/website-integration/client-side-custom-actions). The key must match the function's name in the Widget. The handler gets the function's inputs as one object and returns a result. This example assumes the function's **Inputs** are `sku` set to `{{sku}}` and `quantity` set to `{{quantity}}`:
>
> ```javascript
> window.qwryai("registerTools", {
> addToCart: async ({ sku, quantity }) => {
> try {
> const response = await fetch("/cart/add", {
> method: "POST",
> headers: { "Content-Type": "application/json" },
> body: JSON.stringify({ sku, quantity }),
> });
> if (!response.ok) {
> return { status: "error", error: "Could not add to cart" };
> }
> const cart = await response.json();
> return { status: "success", data: { cartCount: cart.itemCount } };
> } catch {
> return { status: "error", error: "Could not add to cart" };
> }
> },
> });
> ```
>
> The result must have one of these two shapes. Anything else counts as an error.
>
> | Result | Shape |
> | :- | :- |
> | Success | `{ status: "success", data: { ... } }` |
> | Error | `{ status: "error", error: "message" }` |
>
> Add a field from `data`, such as `cartCount`, to the **Return schema** to save it into a Widget variable of the same name, ready for the Widget and its **On success** follow-up.
>
> When **Wait for response** is off, the Widget doesn't wait for your handler and runs **On success** straight away, so the handler's result is ignored.
>
> > [!WARNING]
> >
> > * Register all your functions in a **single** `registerTools` call. Each call replaces the functions registered before it.
> > * Return `{ status: "error", error }` instead of throwing.
> > * **On failure** can't read fields from your handler's result.
>
> > [!NOTE]
> >
> > Using Center Stage? Register the same handlers with `window.qwryCenterStage("registerTools", { ... })`.
> [accordion] Send message
>
> Sends a message to the chat on the visitor's behalf.
>
> | Setting | Description |
> | :- | :- |
> | **Message template** | The message. Insert values with `{{fieldName}}` [template tokens](#template-tokens). |
> | **Hide message from chat** | Sends the message in the background without showing it in the chat. |
> | **On execute** | [Follow-up](#after-a-function-runs) that runs with the message. |
> | **Additional inputs** | Values passed in where the function is used. See [Additional Inputs](#additional-inputs). |
> [accordion] Open link
>
> Opens a web page in a new tab, an email, or a phone call.
>
> | Setting | Description |
> | :- | :- |
> | **Link type** | **Website** (an `https://` address), **Email** (`mailto:`) or **Phone** (`tel:`). |
> | **URL** | The address to open. Supports [template tokens](#template-tokens). |
> | **On execute** | [Follow-up](#after-a-function-runs) that runs after the link opens. |
> | **Additional inputs** | Values passed in where the function is used. See [Additional Inputs](#additional-inputs). |
> [accordion] Open embedded page
>
> Opens an HTTPS page in a window inside the chat, such as a booking page.
>
> | Setting | Description |
> | :- | :- |
> | **Page URL** | An `https://` address or a Widget variable. Supports [template tokens](#template-tokens). |
> | **Modal title** | Optional title shown above the page. |
> | **On success** | [Follow-up](#after-a-function-runs) after the page opens. |
> | **On failure** | [Follow-up](#after-a-function-runs) when it can't open. |
> [accordion] Dismiss widget
>
> Closes the Widget. Use it in two ways:
>
> 1. **Directly**: attach it to a button so the visitor can close the Widget.
> 2. **As a follow-up**: close the Widget after another function, for example after a successful API call.
>
> > [!NOTE]
> >
> > Dismissal is remembered in the visitor's browser. A dismissed Widget stays closed after the page reloads.
> [accordion] Set variables
>
> Updates the Widget's variables without any outside call. Use it to store a visitor's choice or move between views.
>
> | Setting | Description |
> | :- | :- |
> | **Variables** | Key-value pairs to set. Values support [template tokens](#template-tokens). |
> | **Additional inputs** | Values passed in where the function is used. See [Additional Inputs](#additional-inputs). |
> [accordion] Submit to action
>
> Sends the form's values to the **Collect data** action that showed this Widget, so the agent can carry on with them.
>
> | Setting | Description |
> | :- | :- |
> | **On success** | [Follow-up](#after-a-function-runs) after the values are sent. |
> | **On failure** | [Follow-up](#after-a-function-runs) when they can't be sent. |
>
> This works only when the Widget is shown by a Collect data action.
## Loading Behavior
Choose how the Widget shows that a function is running by setting `loadingBehavior` in the element's action:
```jsx
```
| Value | Behavior |
| :- | :- |
| **auto** | The default. A form submit covers the Widget with a loading overlay; a button shows its own spinner. |
| **none** | No loading indicator. |
| **self** | The element that was used shows a spinner. |
| **container** | The whole Widget shows a loading overlay. |
## Additional Inputs
Sometimes a function needs a value that depends on where it's used. For example, a list of order items might each have a **Return** button that passes a different `sku` to the same function.
```jsx
{items.map((item) => (
))}
```
Declare each one under **Additional inputs** in the function, with a type of string, number or boolean. Then use it as a [template token](#template-tokens) anywhere the function accepts one, such as the URL, headers, body or parameters. For the example above, write `{{sku}}`.
> [!WARNING]
>
> Additional inputs aren't variables. They exist only while the function runs, and follow-ups can't read them. To keep a value, save it with a **Set variables** function.
## After a Function Runs
Functions can run a follow-up when they finish, and some before they start.
* **Call API**, **Run client-side code** and **Upload file** have three slots: **On start**, **On success** and **On failure**. For **Upload file**, **On start** runs once before the first file, and **On success (per file)** and **On failure (per file)** run for every file, with `{{file.url}}`, `{{file.name}}`, `{{file.size}}`, `{{file.type}}` and `{{file.error}}` available as [template tokens](#template-tokens).
* **Open embedded page** and **Submit to action** have **On success** and **On failure**.
* **Send message** and **Open link** have one **On execute** slot.
Each slot can do one of these:
| Follow-up | Description |
| :- | :- |
| **None** | Nothing else happens. |
| **Dismiss widget** | Closes the Widget. The dismissal is remembered after a reload. |
| **Set variables** | Updates Widget variables. Values can use [template tokens](#template-tokens), including fields the **Return schema** just saved. |
**On start** runs before the call is made, and the variables it sets apply to the Widget straight away, so a `Loading` state shows while the request runs.
A common pattern is a status variable that drives [states](/docs/developer-guides/widgets/states):
| Slot | Set variables |
| :- | :- |
| **On start** | `fetchStatus` to `loading` |
| **On success** | `fetchStatus` to `loaded` |
| **On failure** | `fetchStatus` to `error` |
Then add `Loading`, `Loaded` and `Error` states whose conditions check that `fetchStatus` is **equal to** `loading`, `loaded` or `error`.
> [!TIP]
>
> Reset anything **On start** sets in both **On success** and **On failure**. Otherwise a failed call can leave the Widget stuck on its loading view.
## Template Tokens
Template tokens are placeholders written as `{{fieldName}}` that are replaced with current values when the function runs. Use dot notation for nested values, such as `{{customer.email}}`. They work in any setting that takes dynamic content, including URLs, headers, bodies, messages and variables.
When a setting holds only a token, such as `"{{items}}"`, the value keeps its type: a number stays a number and a list stays a list.
> [!TIP]
>
> Save response fields with the **Return schema**, then use them as tokens in **On success**, such as `{{trackingNumber}}`.
## Results
Every function ends one of two ways:
| Outcome | Description |
| :- | :- |
| **Success** | The function finished. **Call API** and **Run client-side code** save any **Return schema** fields, then run **On success**. |
| **Error** | The function failed. **On failure** runs if it's set; otherwise the visitor sees the error. |
## Next steps
> [card] States | /docs/developer-guides/widgets/states | Show loading, success and error views.
> [card] File Uploads | /docs/developer-guides/widgets/file-uploads | Collect files from visitors.
> [card] Interactive | /docs/developer-guides/widgets/components/interactive | Buttons that run functions.