Create a Dynamic Carousel using Knowledge Base Sources

Output a dynamic carousel card from your Voiceflow knowledge base content.
Created By
W. Williams
Voiceflow Built
INPUT VARIABLES
{
question
}
Enter text or a voiceflow var like {last_utterance}.
{
voiceflowApiKey
}
Get your Voiceflow API Key from the Integrations section within your bot.
{
}
{
}
{
}
{
}
OUTPUT VARIABLES
{
}
{
}
{
}
{
}
{
}
{
}
PATHS
{
unknown
}
{
default
}
{
}
{
}
{
}
{
}

Function Code Snippet


export default async function main({ inputVars }) {

  const response = await fetch( 'https://general-runtime.voiceflow.com/knowledge-base/query', {
    method: 'POST',
    headers: {
      'Authorization': inputVars.voiceflowApiKey,
      'accept': 'application/json',
      'content-type': 'application/json'
    },
    body: JSON.stringify( {
      'question': inputVars.question,
      'synthesis': true
    } )
  } );

  const data = response.json

  // Debug data
  const debug = JSON.parse( JSON.stringify( data ) )
  delete debug[ 'output' ]
  delete debug[ 'chunks' ]
  debug.chunks = data?.chunks?.length || 0

  if ( ! response.ok || data?.output == null ) return {
    next: {
      path: 'unknown'
    },
    trace: [
      { 
        type: 'debug',
        payload: {
          message: 'Debug: ' + JSON.stringify( debug )
        }
      }
    ]
  }

  // Build carousel object
  const carousel = {
    'layout': 'Carousel',
    'cards': []
  }

  data.chunks.forEach( ( chunk ) => {
    if ( chunk.score >= 0.8 && chunk.source.type == 'url' ) {
      carousel.cards.push( {
        imageUrl: 'https://image.thum.io/get/ogImage/noanimate/' + chunk.source.url,
        title: '',
        description: {
          text: ''
        },
        buttons: [
          {
            "name": "Read More",
            "request": {
              "type": "url-button",
              "payload": {
                "label": "Read More",
                "actions": [
                  {
                    "type": "open_url",
                    "payload": {
                      "url": chunk.source.url
                    }
                  }
                ]
              }
            }
          }
        ]
      } )
    } 
  } )

  // Return carousel
  return {
    next: {
      path: 'default'
    },
    trace: [ 
      {
        type: 'debug',
        payload: {
          message: 'Debug: ' + JSON.stringify( debug )
        }
      },
      {
        type: 'text',
        payload: {
          message: data.output
        }
      },
      { 
        type: 'carousel',
        payload: carousel
      } 
    ]
  }

}

Function Walkthrough