Alchemy RecipeBeginnerguide

Building Your First Customer Support Chatbot: A Step-by-Step Setup Guide

Published

Customer support can consume significant resources, particularly for small teams handling high volumes of repetitive enquiries. A chatbot handles common questions, reduces response times, and frees your team to focus on complex issues that require human judgment. This guide walks you through building a functional customer support chatbot from scratch, requiring no previous coding experience....... For more on this, see Building Your First AI Chatbot for Customer Support: A Pr.... For more on this, see Customer support ticket analysis and response automation.

You'll create a chatbot that answers frequently asked questions, collects customer information, and escalates issues to your support team when necessary. The combination of tools covered here strikes a balance between ease of use and functionality, allowing you to launch within hours rather than weeks.

Whether you manage an e-commerce site, SaaS product, or service business, this approach suits you. By the end, you'll have a working chatbot deployed on your website or messaging platform.

What You'll Need

Before starting, gather the following:

  • A text editor or IDE (Visual Studio Code is free and popular)
  • An OpenAI account (free tier works initially, though you'll likely pay small amounts once live)
  • Accounts with MindStudio and TheBai (both offer free trials)
  • Twig template access (usually bundled with hosting or available via CDN)
  • Your customer support FAQ documentation (aim for 10-20 common questions initially)
  • A basic website or messaging platform where the chatbot will operate
  • 2-3 hours of uninterrupted setup time

Budget considerations: MindStudio free tier supports basic chatbots with monthly limits; OpenAI charges per token (roughly £0.50-£2 monthly for small-scale support); TheBai offers a free plan with rate limits; Twig is free. For a bootstrapping operation, you'll spend nothing initially, then roughly £5-15 monthly once you scale beyond free tier limits.

Step-by-Step Setup

Phase 1:

Preparing Your Knowledge Base

Your chatbot only performs well with quality source material. Start by documenting your 10-20 most common customer questions and answers. Structure these clearly:


Q: What are your business hours?
A: We operate Monday to Friday, 09:00-17:00 GMT. Emails sent outside these hours receive replies the next working day.

Q: How do I reset my password?
A: Visit our login page, click "Forgot Password", enter your email, and follow the link sent to your inbox within 5 minutes.

Q: What's your refund policy?
A: We offer 30-day full refunds on unused products. Used items are eligible for 50% refunds within 14 days.

Save this as a plain text or Markdown file. You'll reference it throughout the setup. Avoid vague answers; specificity improves chatbot accuracy significantly.

Phase 2:

Setting Up MindStudio

MindStudio provides a visual interface for building chatbots without coding. Start here if you've never built conversational AI.

  1. Visit mindstudio.io and create a free account.

  2. Click "Create New App" and select "Chatbot".

  3. Name your bot something descriptive like "Support Assistant" or "Customer Help Bot".

  4. In the training section, paste your FAQ content. MindStudio analyses this text and builds its response patterns accordingly.

  5. Under "Personality", set a tone: professional, friendly, or formal. For support, professional-friendly works best.

  6. Configure the following settings:

Response Confidence Threshold: Set to 0.7 (the chatbot only answers if 70% confident; otherwise it escalates).

Escalation Trigger: Specify the exact phrase that routes to your team. "Connect me with an agent" is clear and unambiguous.

  1. Test the chatbot in the preview panel. Ask it your FAQ questions and verify responses match your documentation.

Example interaction to test:


User: What's your refund policy?
Bot: We offer 30-day full refunds on unused products. Used items are eligible for 50% refunds within 14 days.

If the response drifts from your source material, add clarifying examples to your knowledge base and retrain.

Phase 3:

Integrating OpenAI Codex for Enhanced Understanding

OpenAI Codex improves the chatbot's ability to understand variations of the same question. Rather than requiring exact phrasing, it contextually matches intent.

  1. Create an OpenAI account at platform.openai.com.

  2. Generate an API key in your account settings. Store this securely; never commit it to public code repositories.

  3. In MindStudio's integration settings, select "OpenAI API Integration".

  4. Paste your API key. MindStudio now uses GPT models to refine understanding.

  5. Create a simple Node.js service to moderate responses. This prevents the model from answering out-of-scope questions:

const { Configuration, OpenAIApi } = require("openai");

const configuration = new Configuration({
  apiKey: process.env.OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);

async function moderateResponse(userInput, knowledgeBase) {
  const prompt = `Given this knowledge base:\n${knowledgeBase}\n\nDoes this customer question fall within our support scope?\nQuestion: "${userInput}"\n\nRespond with "yes" or "no".`;
  
  const response = await openai.createCompletion({
    model: "text-davinci-003",
    prompt: prompt,
    max_tokens: 5,
    temperature: 0,
  });

  return response.data.choices[0].text.trim().toLowerCase() === "yes";
}

module.exports = { moderateResponse };

This function checks whether the customer's question relates to your support topics before the chatbot attempts a response.

Phase 4:

Setting Up TheBai for Data Persistence

TheBai stores conversation history, enabling the chatbot to maintain context across multiple messages. This matters when customers ask follow-up questions.

  1. Create a TheBai account at thebai.com.

  2. Create a new database called "support_conversations".

  3. Define two tables:

Table: conversations

ColumnTypeNotes
conversation_idStringUnique identifier
customer_idStringLinks to customer
start_timeTimestampWhen conversation began
statusStringopen, resolved, or escalated

Table: messages

ColumnTypeNotes
message_idStringUnique identifier
conversation_idStringForeign key to conversations
senderStringbot or customer
contentTextMessage body
timestampTimestampWhen sent
  1. Generate API credentials for your chatbot application.

  2. Use this code snippet to save conversation data:

const axios = require("axios");

async function logMessage(conversationId, sender, content) {
  const payload = {
    conversation_id: conversationId,
    sender: sender,
    content: content,
    timestamp: new Date().toISOString(),
  };

  try {
    await axios.post(
      "https://api.thebai.com/v1/messages",
      payload,
      {
        headers: {
          Authorization: `Bearer ${process.env.THEBAI_API_KEY}`,
        },
      }
    );
  } catch (error) {
    console.error("Failed to log message:", error);
  }
}

module.exports = { logMessage };

This function runs after every customer message and bot response, creating an audit trail for analysis.

Phase 5:

Templating Responses with Twig

Twig is a templating engine that allows dynamic, personalised responses. Instead of static text, your chatbot tailors answers to individual customers.

  1. Install Twig in your project:
npm install twig
  1. Create a file called response_templates.twig with dynamic templates:
{% if question_type == 'refund' %}
Dear {{ customer_name }},

Thank you for your enquiry. Here's our refund policy:

We offer 30-day full refunds on unused products. Used items are eligible for 50% refunds within 14 days. To process your refund, please reply with your order number, and we'll handle it within 2-3 working days.

Best regards,
Support Team

{% elseif question_type == 'hours' %}
{{ customer_name }}, we're available Monday to Friday, 09:00-17:00 GMT. Outside these hours, we'll respond to your email the next working day.

{% elseif question_type == 'password_reset' %}
{{ customer_name }}, here's how to reset your password:

1. Visit our login page
2. Click "Forgot Password"
3. Enter your email address
4. Check your inbox for a reset link (arrives within 5 minutes)
5. Follow the link and create a new password

If you don't see the email, check your spam folder.
{% endif %}
  1. Load and render these templates in your chatbot logic:
const Twig = require("twig");

async function generateResponse(questionType, customerData) {
  const template = Twig.twig({
    path: "./response_templates.twig",
  });

  const rendered = template.render({
    question_type: questionType,
    customer_name: customerData.first_name,
  });

  return rendered;
}

module.exports = { generateResponse };

Phase 6:

Putting It Together

Create a main orchestration file that ties all components together:

const { moderateResponse } = require("./openai-moderator");
const { logMessage } = require("./thebai-persistence");
const { generateResponse } = require("./twig-templates");

const knowledgeBase = `
Q: What are your business hours?
A: Monday to Friday, 09:00-17:00 GMT.

Q: How do I reset my password?
A: Visit login, click Forgot Password, check your email.

Q: What's your refund policy?
A: 30-day full refunds on unused items. 50% refund on used items within 14 days.
`;

async function handleCustomerMessage(conversationId, customerData, userInput) {
  // Step 1: Check if question is in scope
  const inScope = await moderateResponse(userInput, knowledgeBase);

  if (!inScope) {
    const response = "I'm not able to help with that query. Please contact our support team at support@yourcompany.com.";
    await logMessage(conversationId, "bot", response);
    return response;
  }

  // Step 2: Determine question type
  const questionType = classifyQuestion(userInput);

  // Step 3: Generate personalised response
  const response = await generateResponse(questionType, customerData);

  // Step 4: Log the exchange
  await logMessage(conversationId, "customer", userInput);
  await logMessage(conversationId, "bot", response);

  return response;
}

function classifyQuestion(input) {
  const lowerInput = input.toLowerCase();
  
  if (lowerInput.includes("refund") || lowerInput.includes("money back")) {
    return "refund";
  } else if (lowerInput.includes("hours") || lowerInput.includes("open") || lowerInput.includes("available")) {
    return "hours";
  } else if (lowerInput.includes("password") || lowerInput.includes("reset") || lowerInput.includes("login")) {
    return "password_reset";
  }
  
  return "general";
}

module.exports = { handleCustomerMessage };

Phase 7:

Deployment

For a quick start, deploy to Heroku or Railway:

git init
git add .
git commit -m "Initial chatbot setup"
heroku create your-chatbot-name
git push heroku main

Alternatively, embed directly in your website using a widget. MindStudio provides embed code you paste into your site's HTML.

Tips and Pitfalls

Avoid Overfitting to Exact Questions: Your chatbot learns from FAQ content, but customers rarely phrase questions identically. Use variations in your training data. Instead of just "What's your refund policy?", add "How do I get my money back?", "Can I return my purchase?", and "Do you offer refunds?".

Set Realistic Confidence Thresholds: If your threshold is too high (0.9+), the chatbot escalates everything. Too low (0.5), and it confidently answers incorrect information. Start at 0.7 and adjust based on testing.

Monitor Escalations: When customers request a human agent, log these conversations and analyse them weekly. If a topic appears repeatedly, it belongs in your FAQ.

Personalisation Matters, but Keep It Simple: Using the customer's name feels human. Avoid over-personalisation like predicting what they'll ask next; that often backfires.

Test Before Going Live: Run 50+ test conversations with colleagues, asking various phrasings and edge cases. Note failures and retrain.

Keep Response Times Brief: Customers expect immediate replies from chatbots. If your system takes more than 2 seconds to respond, they perceive it as slow.

Version Your Knowledge Base: When you update FAQs, date the changes. If a customer reports the chatbot gave outdated information, you'll know which version caused the problem.

Cost Breakdown

ToolPlanMonthly CostNotes
MindStudioFree£0Handles up to 100 conversations/month; sufficient for testing. Paid plans start at £20/month for higher limits.
OpenAI APIPay-as-you-go£2-10Roughly £0.002 per 1,000 tokens. A typical conversation uses 500-2,000 tokens. Budget £10/month safely.
TheBaiFree£0Includes 1GB storage; fine for most small support operations. Paid tier is £15/month for 50GB.
TwigFree (self-hosted)£0No ongoing fees if you host it yourself. No licensing restrictions.
Hosting (Heroku/Railway)Free tier£0-7Free tier covers light usage. Paid dynos start at £7/month for reliability.
Total for Beginner Setup£0-20Starting completely free; scaling to £20-25 as you grow.

For a small business handling 100-500 support queries monthly, budget £15-25. For higher volumes, costs remain linear with usage.

Summary

Building a customer support chatbot needn't be complex or expensive. Using MindStudio for the interface, OpenAI Codex for understanding variations, TheBai for conversation history, and Twig for personalisation, you've created a system that handles repetitive enquiries efficiently whilst knowing when to escalate to your team. Test thoroughly before launch, monitor escalations to refine your knowledge base, and adjust confidence thresholds based on real-world performance. You'll recover the small setup time investment within weeks through reduced support workload.

More Recipes