Carousel modality

From start to finish, provide a chat Carousel modality with NLX Touchpoint

What's a Modality?

A modality allows for information to be transmitted to a user that goes beyond a standard message. Images, audio, structured text, haptic signals, videos, and more can be modalities you may want to provide users during conversation.

In chat applications, carousels are useful for providing users with a selection of options enriched with media and text information:

  • Offer hotel room options in a booking conversation

  • Show location options in a venue search conversation

Each option in a carousel is represented as a card, and with a Touchpoint conversation, you can configure a carousel for users to select between one of several cards. Each card in the carousel typically contains:

  • An id (UUIDv4 is recommended)

  • An image or visual

Show me the code
  • Example requires a schema and modality matching the guide.

  • Notice in the HTML file below:

    • Line 27: The CarouselExample defined above

    • Line 73: The CarouselExample set in the customModalities object

  • Update the HTML file

    • Line 61: with your applicationUrl

    • Line 63: with your nlx-api-key

<head> 
  <style>
    body {
      background-color: #f8f9fa;
    }
  </style>
</head>
<body>
  <script defer src="https://unpkg.com/@nlxai/touchpoint-ui/lib/index.umd.js"></script>
  <script type="module">
    const contentLoaded = () => {
      if (document.readyState === "loading") {
        return new Promise((resolve) => {
          window.addEventListener("DOMContentLoaded", () => {
            resolve();
          });
        });
      } else {
        return Promise.resolve();
      }
    };

    await contentLoaded();
    
    const { html, create, React } = nlxai.touchpointUi;
    
    const CarouselExample = ({ data, conversationHandler }) => {
      const [selected, setSelected] = React.useState(null);
      const carousel = html`
        <Carousel>
          ${data.map((cardData, cardIndex) => html`
            <CustomCard
              key=${cardIndex}
              selected=${selected === cardIndex}
              onClick=${() => {
                setSelected(cardIndex);
                conversationHandler.sendChoice(cardData.id);
              }}
            >
              <CustomCardImageRow
                src=${cardData.imageUrl}
                alt="Alt Text"
              />
              <CustomCardRow
                left=${html`
                  <BaseText>${cardData.leftText}</BaseText>
                `}
                right=${html`
                  <BaseText>${cardData.rightText}</BaseText>
                `}
              />
            </CustomCard>`
        )}
      </Carousel>`;
      return carousel;
    };

    const touchpointOptions = {
      config: {
        applicationUrl:
          "https://bots.studio.nlx.ai/c/..", // YOUR APPLICATION URL
        headers: {
          "nlx-api-key": "QkeLasdf389793", // YOUR API KEY
        },
        languageCode: "en-US",
      },
      windowSize: "full",
      colorMode: "light",
      theme: {
        accent: "purple"
      },
      customModalities: { 
        ExampleCarouselModality: CarouselExample
      }
    };
    const touchpoint = await create(touchpointOptions);
  </script>
</body>

Checklist

You'll complete the following to successfully launch your application with a carousel Touchpoint:


For this guide, you may use the provided static schema or use your own when setting up a Data request:

  • Select Resources in workspace menu > Choose Data requests > New data request > Provide the name ExampleCarouselDataRequest

  • Switch to Static implementation under the Implementation tab (or switch to External if using own schema)

  • Copy and paste the full schema below into the JSON Response field

  • Select the Response model tab > Choose <> Auto-generate option

  • Click Set response model > Click Save

[
  {
    "id": "c45a0eb6-f132-4365-bec2-7efacca39f8c",
    "imageUrl": "https://picsum.photos/200/300?random=1",
    "leftText": "Example Left Text",
    "rightText": "Example Right Text"
  },
  {
    "id": "623c9b3d-1e15-4352-9630-b895e0a0e70f",
    "imageUrl": "https://picsum.photos/200/300?random=2",
    "leftText": "Beispiel Linker Text",
    "rightText": "Beispiel Rechter Text"
  },
  {
    "id": "9bbab9a9-7008-4308-b305-82140bed928f",
    "imageUrl": "https://picsum.photos/200/300?random=3",
    "leftText": "Texto Izquierdo de Ejemplo",
    "rightText": "Texto Derecho de Ejemplo"
  }
]

This sample schema of listed objects represents three cards:

  • id: UUID of the card within the carousel

  • imageUrl: Uses picsum for a unique image

  • leftText: Text to be rendered on the left portion of each card

  • rightText: Text to be rendered on the right portion of each card


NLX uses Modalities to pass structured data over channels. Touchpoint uses modalities to indicate which component should be rendered when enabled within a node of a flow.

For this modality, you'll use the same schema from Step 1:

Modality with sample carousel schema
  • Select Resources in workspace menu > Choose Modalities > New modality > Provide the name ExampleCarouselModality

  • Click <> Auto-Generate option

  • Copy and paste the schema from Step 1 > Choose Set schema

  • Click Save


Next, you'll use the resources created in the previous steps within a simple conversation flow that presents options to a user via the carousel modality and repeats their selection back to them.

Sample Touchpoint Carousel flow
  • Select Flows in workspace menu > Create a new flow named ExampleCarouselFlow

  • Within the flow's Canvas, open the Settings icon > Under the Training phrases tab, disable Enable training toggle

  • Add and link a Basic node to the Start node > Provide a message on the Basic node (try "Hello! Here is a carousel demo")

  • Add and link a Data request node to your Basic node > Set the request to the ExampleCarouselDataRequest created in Step 1

  • Add and link a User choice node to the Data request node's Success edge. On the User choice node's side panel, configure the following:

    • Resolve dropdown: Select ExampleCarouselDataRequest

    • Choose field: Enter UserCarouselChoice

    • Choice label and Choice ID fields: Enter curly brace { and select {id} from the options

    • + Add message: Enter "Select a card:"

    • Click Add functionality > Select Modalities

    • Toggle Enable for ExampleCarouselModality

      • Click the Tt on the right of the text field and swap to (x) PlaceHolders

      • Set the placeholder dropdown to ExampleCarouselDataRequest

  • Add and link another Basic node from the User choice node's Match edge:

    • + Add message: Enter "You selected: {UserCarouselChoice.id} with {UserCarouselChoice.leftText}".

Open the placeholder menu by typing { and selecting from the options.


Step 4: Deploy an application

To employ the conversation flow with your carousel, you'll need to create your conversational AI application.

  • Select Applications from workspace menu > Choose New application > Enter the name ExampleCarouselApplication

  • Under the Flows tab, attach the ExampleCarouselFlow > Click Save

  • Select the Default behavior tab > Toggle Welcome behavior to Flow > Choose ExampleCarouselFlow > Click Save

  • Select the Channels tab > Expand API channel > Enter the name ExampleCarouselAPIChannel

    • <> Auto-generate an API key

    • Add the following to Whitelisted domains:

      • https://preview-html.playcode.io

      • https://playcode.io/html

  • Click Create channel

  • Select the Deployment tab > Create a build > Select an NLP engine from the dropdown > Choose Create build

  • After a successful build, select Deploy

Application API channel setup

Your Touchpoint Component will:

  • Iterate and render a card for each object from the list set in ExampleCarouselDataRequest

  • Use the conversationHandler to send the selection back to the NLX client

  • Use the React useState feature to highlight the user's choice

You'll use the CustomCards and the HTML feature of Touchpoint to build a simple example.

Touchpoint Component Example Code

const CarouselExample = ({ data, conversationHandler }) => {
  const [selected, setSelected] = React.useState(null);
  const carousel = html`
    <Carousel>
      ${data.map((cardData, cardIndex) => html`
        <CustomCard
          key=${cardIndex}
          selected=${selected === cardIndex}
          onClick=${() => {
            setSelected(cardIndex);
            conversationHandler.sendChoice(cardData.id);
          }}
        >
          <CustomCardImageRow
            src=${cardData.imageUrl}
            alt="Alt Text"
          />
          <CustomCardRow
            left=${html`
              <BaseText>${cardData.leftText}</BaseText>
            `}
            right=${html`
              <BaseText>${cardData.rightText}</BaseText>
            `}
          />
        </CustomCard>`
    )}
  </Carousel>`;
  return carousel;
};

Now you're ready to test your carousel live! This next step uses the service, PlayCode, to run the sample HTML.

  • From your application's Deployment tab in NLX, choose Details next to the Deployed status

  • Save your Application URL and API Key

  • Copy the entire HTML file and paste into PlayCode's editor

  • Notice in the HTML file below:

    • Line 27: The CarouselExample defined above

    • Line 73: The CarouselExample set in the customModalities object

  • Update the HTML file

    • Line 61: with your applicationUrl

    • Line 63: with your nlx-api-key

  • Click the green Play button â–¶

    • Then select "Hard Restart" to start the demo

  • Open Touchpoint and experience the rendered demo

<head> 
  <style>
    body {
      background-color: #f8f9fa;
    }
  </style>
</head>

<body>
  <script defer src="https://unpkg.com/@nlxai/touchpoint-ui/lib/index.umd.js"></script>
  <script type="module">
    const contentLoaded = () => {
      if (document.readyState === "loading") {
        return new Promise((resolve) => {
          window.addEventListener("DOMContentLoaded", () => {
            resolve();
          });
        });
      } else {
        return Promise.resolve();
      }
    };
    
    await contentLoaded();
    
    const { html, create, React } = nlxai.touchpointUi;
    const CarouselExample = ({ data, conversationHandler }) => {
      const [selected, setSelected] = React.useState(null);
      const carousel = html`
        <Carousel>
          ${data.map((cardData, cardIndex) => html`
            <CustomCard
              key=${cardIndex}
              selected=${selected === cardIndex}
              onClick=${() => {
                setSelected(cardIndex);
                conversationHandler.sendChoice(cardData.id);
              }}
            >
              <CustomCardImageRow
                src=${cardData.imageUrl}
                alt="Alt Text"
              />
              <CustomCardRow
                left=${html`
                  <BaseText>${cardData.leftText}</BaseText>
                `}
                right=${html`
                  <BaseText>${cardData.rightText}</BaseText>
                `}
              />
            </CustomCard>`
        )}
      </Carousel>`;
      return carousel;
    };

    const touchpointOptions = {
      config: {
        applicationUrl:
          "https://bots.studio.nlx.ai/c/..", // YOUR APPLICATION URL
        headers: {
          "nlx-api-key": "QkeLasdf389793", // YOUR API KEY
        },
        languageCode: "en-US",
      },
      windowSize: "full",
      colorMode: "light",
      theme: {
        accent: "purple"
      },
      customModalities: { 
        ExampleCarouselModality: CarouselExample
      }
    };
    const touchpoint = await create(touchpointOptions);
  </script>
</body>

Last updated