Welcome to our latest video series, "How to Build a ChatGPT-powered Recipe Chatbot with Botpress."

In this series, we'll walk you through the process of creating a ChatGPT recipe chatbot from scratch, leveraging Botpress' powerful generative AI features. Our step-by-step video series is designed to help beginner builders unlock the full potential of Botpress and ChatGPT. 

Throughout these videos, you'll learn essential chatbot building skills such as capturing user information, making API calls, displaying content in carousels, and harnessing the power of AI Tasks to design interactive, engaging conversations.

The video series might be all about a recipe chatbot, but don't worry – the skills you'll pick up can be used in many other situations: hotel bookings, insurance quotes, customer service chats – you name it. They all pretty much use the same three-part structure when talking with users. So, as you build along with us, you'll be well on your way to creating your own ChatGPT chatbot for your organization, no matter what industry or application you have in mind.

Video Series Breakdown

Video 1: Overview

In the first video of the Recipe Bot video series, our very own Gordy from Botpress introduces the chatbot project we'll be building together. This chatbot is designed to help users figure out their dinner plans by recommending recipes based on their preferences. Gordy takes us through the three main sections of the chatbot: capturing user information, using an API to fetch recipes, and providing contextual Q&A

One of the most interesting features Gordy highlights is the AI Task card, which leverages ChatGPT to simplify the chatbot building process, making it faster and easier than ever before. By the end of the first video, you'll be eager to dive into the rest of the series, where we'll create a new bot and build the recipe chatbot from scratch.

Video 2: Capturing Information

In the second video of our series, Gordy jumps right into the first stage of building our chatbot: capturing user information. He guides us through the process of creating a new bot and cleaning up the default template to provide a clean slate for the project. To plan out the chatbot, Gordy creates empty nodes for each task, starting with greeting the user, asking the number of people, inquiring about dietary preferences, and finally getting a recipe search query. 

Gordy demonstrates how to use the "capture card" to extract user information, such as the number of people, and store it in a variable. He then moves on to capturing dietary preferences by creating custom options for the user to choose from. The final step involves leveraging ChatGPT to handle the recipe search query. By using an AI Task card, Gordy instructs ChatGPT to classify the user's input and extract relevant keywords. 

Throughout the video, Gordy tests each step in the Botpress emulator to ensure everything works as intended. With the basic skeleton of the bot in place, the stage is set for the upcoming video, where we'll learn how to use the "Execute Code" card to call an external API and fetch real-world recipes for the user. Stay tuned for more exciting bot-building adventures!

Video 3: Calling an external API

In the third video of the series, Gordy continues to build the chatbot using Botpress Studio's generative AI features. In this episode, he focuses on using an external API to fetch real-world data based on the user's input. The API being used is Spoonacular, which offers a large food database and a generous free tier.

After signing up for Spoonacular and obtaining an API key, Gordy demonstrates how to use environmental variables in the Botpress Studio to securely store and manage the API key. Next, he outlines a plan for calling the API and processing the data. 

To write the code needed for making the API call, Gordy leverages Botpress’ GPT "Execute Code" function. By providing a detailed prompt, he gets GPT to generate the necessary code, which includes handling the API call parameters and saving the results to the workflow. He then modifies a node to display the API call results as text. 

Upon testing the chatbot in the emulator, the API call successfully retrieves a large amount of information. In the next video, Gordy will focus on transforming this data into a visually appealing carousel, presenting the user with a more digestible and engaging experience.

Video 4: Displaying content dynamically in a carousel

After fetching data from Spoonacular’s external API in the previous video, the focus of this fourth video is parsing the data and converting it from a large block of text into a visually appealing carousel. Gordy demonstrates what a completed carousel looks like, with images, titles, and buttons for each recipe. The challenge is to turn the raw data from the API into this user-friendly format. 

To create the carousel, Gordy once again employs Botpress’ GPT "Execute Code" function to help write the necessary code. While the generated code requires some manual tweaking, GPT provides a solid starting point. He then moves on to writing code for handling different numbers of recipes returned by the API and shows how GPT can be used for transitions as well.

After setting up the necessary nodes and populating them with the correct variable names, Gordy tests the chatbot and successfully generates a carousel with three recipe cards. 

Video 5: Calling an external API

The focus of the fifth video is integrating ChatGPT to power contextual Q&A, allowing users to ask questions about the recipes obtained from Spoonacular API and receive relevant, accurate answers.

To achieve this, Gordy plans out a series of nodes to prompt users for questions, answer them using ChatGPT, and ask if users have any more questions. He demonstrates the process of setting up the AI tasks and transitions, emphasizing the importance of providing contextual information and giving the AI an "out" to combat hallucination issues.

Gordy shows how to create a chat history variable by running a piece of code, ensuring that the chatbot respects the 5,000-character prompt limit. He then tests the chatbot by asking it various questions about the recipes, and the AI successfully provides accurate and contextually relevant answers.

Video 6: Publishing and Sharing your Bot

The sixth video in our series shifts from bot building to bot sharing. Gordy goes on to explain how to publish and embed the Recipe bot on a website, allowing a larger audience to engage with the chatbot. With just a click, the Botpress Cloud Studio allows us to publish the bot, and then we can distribute a link for others to interact with the bot using the "Share" button.

To integrate the bot into a website, Gordy demonstrates the use of the web channel in the Botpress Admin dashboard. He copies the provided code and embeds it into a GitHub page, making the bot accessible directly from the website.

Video 7: Giving your bot a personality with AI

In the seventh video of the series, Gordy shows how we can improve how engaging the Recipe Bot is by using the AI Personality feature. The aim of giving the Recipe Bot a personality is to transform it into a lively conversationalist, avoiding repetitive interactions.

Infusing a bot with different greetings or question styles previously involved manual crafting, which could be quite time intensive. With the AI Personality feature in Botpress the process becomes a lot easier.

Gordy navigates to the chatbot settings and demonstrates the 'Personality Rewrite'. By describing the type of personality desired - in this case, a cartoon chef from an animated kids film - he's able to influence the bot's communication style, including the use of emojis. 

The beauty of the AI Personality feature is that it enables a consistent bot personality to shine throughout the conversation, no matter what direction it takes.

Video 8: How to handle conversational failures

In the eighth video of the Recipe Bot series, Gordy dives into the concept of 'fallbacks'—essential contingency plans designed to handle unexpected user responses and non-cooperative users. The goal? To create more robust and resilient conversational flows with our Recipe Bot.

Gordy begins by identifying possible issues in the bot's initial question, such as when a user provides unclear or unusual answers. To address this, the Studio provides a simple solution: retries. By increasing the number of retries, we can subtly escalate the detail in our prompt to seek a more precise answer from the user.

However, retries alone aren't always sufficient. For scenarios where a user provides unfeasible answers (e.g., requiring a recipe for a million people), Gordy introduces the concept of validation. Validation allows us to define precise rules about the data a capture card extracts. 

The third layer of fallback planning involves transitions to handle failure, which can be added if the bot fails to extract the correct information from the user after the retries have been exhausted. This prevents the bot from becoming stuck in a loop repeating the same question, and instead allows the conversation to progress naturally.

Video 9: Chain of Thought Prompting

In the ninth installment of the series, Gordy takes the Recipe Bot to the next level by enhancing the robustness of its AI Tasks and addressing AI hallucinations.

At the beginning of the video, Gordy presents an interesting challenge—what if a user requests something unrelated to our bot's purpose, like a Minecraft recipe? To handle such out-of-scope queries and prevent unnecessary API calls, Gordy implements a classification task. This initial task filters the user's message, determining whether it's a 'food recipe' request or 'out of scope'. We then use a transition to create a fallback node to catch out-of-scope questions and inform the user about the bot's specific function.

The second part of the video dives into a fascinating AI challenge: AI hallucinations. These occur when an AI model like ChatGPT confidently asserts something factually incorrect. Gordy proposes two strategies to combat this— (1) providing factual information in the prompt and (2) employing a technique called Chain of Thought prompting.

Developed by Google, Chain of Thought prompting breaks down complex problems into smaller components. Each of these components is then processed through the AI, and the responses are used to generate a final, factually accurate answer. Gordy demonstrates how to implement this technique in the Studio, enhancing the Recipe Bot's accuracy, especially for complex user queries.

Video 10: How to use the Recipe Bot template

In the tenth and final video of the series, Gordy takes the Recipe Bot journey full circle. He begins by showing us how to access the bot we’ve seen built from the ground up within the Botpress Studio.

Next, we’re introduced to a critical component to get the bot template working—adding an API key. After creating an account with Spoonacular and obtaining the key, it's added to the bot in the Studio, and just like that the Recipe Bot is now ready to handle culinary questions.

The template bot comes equipped with all the features demonstrated in the series, including the Chain of Thought workflow. However, if you'd like the bot to offer just the final answer without the entire Chain of Thought process, Gordy shows how you can easily modify the workflow.

The final video emphasizes the flexibility and adaptability of Botpress, showcasing how a bot template –packed with a rich set of features - can jumpstart the bot building process from idea to fully functioning proof of concept.

Code Snippets

Code Snippet that appears in Video 3 to call Spoonacular API

var options = {
  method: 'GET',
  url: 'https://api.spoonacular.com/recipes/complexSearch',
  params: {
    query: workflow.baseQuery,
    diet: encodeURIComponent(workflow.dietType),
    apiKey: env.apiKey,
    number: '3',
    ignorePantry: 'false',
    sort: 'popularity',
    sortDirection: 'asc',
    addRecipeInformation: 'true',
    addRecipeNutrition: 'false'
  }
}
const response = await axios.request(options)
if (response.status == 200) {
  workflow.recipes = response.data.results
} else {
  console.log(`API call failed with status code ${response.status}`)
}

Code Snippet that appears in Video 4 to render recipe carousel

workflow.recipes = []
const myCards = workflow.recipeInfo.map((recipe) => {
  workflow.recipes.push({
    title: recipe.title,
    vegetarian: recipe.vegetarian,
    vegan: recipe.vegan,
    glutenFree: recipe.glutenFree,
    dairyFree: recipe.dairyFree,
    veryHealthy: recipe.veryHealthy,
    cheap: recipe.cheap,
    veryPopular: recipe.veryPopular,
    readyInMinutes: recipe.readyInMinutes,
    servings: recipe.servings,
    summary: recipe.summary
  })
  // create the card object
  return {
    type: 'card',
    title: {
      dynamicValue: `${recipe.title}`,
      valueType: 'dynamic'
    },
    subtitle: {
      dynamicValue: '',
      valueType: 'dynamic'
    },
    imageUrl: {
      dynamicValue: `${recipe.image}`,
      valueType: 'dynamic'
    },
    actions: [
      {
        action: 'url',
        label: 'View Recipe',
        value: `${recipe.sourceUrl}`
      }
    ]
  }
})
workflow.cards = []
for (var card of myCards) {
  workflow.cards.push({
    //in order to render a card, we only need these three fields
    title: card.title,
    imageUrl: card.imageUrl,
    actions: card.actions[0]
  })
}

Code Snippet that appears in Video 5 to prepare Chat History

workflow.chatHistory = []
event.state.session.history.map((message) => {
  if (message.preview != 'What would you like to know about these recipes?') {
    workflow.chatHistory.push(`${message.sender}:${message.preview}`)
  }
})

const myStr = `Using the provided recipe information and chat history as context, try to answer the question as honestly as possible. If you don't know the answer, say "I don't know." 

Your answer should be friendly and complete, using the same words from the question as much as possible.
Recipe info: ${JSON.stringify(workflow.recipeInfo)}
Chat history: ${JSON.stringify(workflow.chatHistory)}
User question: ${event.preview}}`
console.log(`The prompt is ${myStr.length} characters long`)
if (myStr.length > 5000) {
  console.log('The prompt is too long! Omitting the chat history...')
  workflow.chatHistory = []
}

Conclusion

In this comprehensive video series, Gordy explored the process of building a ChatGPT-powered recipe chatbot using Botpress. The series covered essential chatbot building techniques such as capturing user information, making API calls, displaying content in carousels, and harnessing the power of AI Tasks to create interactive, engaging conversations. We also delved into more advanced topics like integrating ChatGPT for contextual Q&A, infusing the bot with a lively personality, creating fallbacks, and performing chain of thought prompting.

If you haven't already, we invite you to explore the video series and start building your own chatbots using Botpress. The skills and techniques shown while building the recipe bot are transferable to a variety of chatbot applications across different industries. With the series complete, we encourage you to join us in our next bot building series!

With the power of ChatGPT and Botpress at your fingertips, you're now well-equipped to create dynamic, engaging chatbots that cater to your organization's specific needs. Get started – it's free!

Happy bot-building!

Build better with Botpress

Get started today - it's free!

Related Articles

Culture
December 21, 2021

What’s Happening at Botpress: October 2021 Recap

Find out all about our October 2021 events, product updates, tips, tools, tricks and tutorials — All in one place.

Industry
November 15, 2021

Three Key Advantages of Using a Framework

The chatbot development ecosystem is still relatively immature, which means it’s not as easy as it will eventually be...

Industry
April 8, 2022

Nine Reasons Why You Should Use Chatbots for Your Business

As a business owner Sarah was eager to use new technologies to give customers new ways of interacting with the...

© Botpress 2023