Salesforce gives Slackbot 30 new AI powers, and a strategy that looks a lot like Microsoft’s
Back to Tutorials
techTutorialbeginner

Salesforce gives Slackbot 30 new AI powers, and a strategy that looks a lot like Microsoft’s

April 5, 20266 views7 min read

Learn to build a basic AI chatbot with intent recognition and web interface, similar to Salesforce's new Slackbot capabilities.

Introduction

In this tutorial, you'll learn how to create a basic AI-powered chatbot similar to the new Slackbot features announced by Salesforce. We'll build a simple conversational AI assistant that can understand user intents and respond appropriately. This tutorial will teach you fundamental concepts of natural language processing (NLP) and how to implement basic AI capabilities in chatbots.

Prerequisites

To follow this tutorial, you'll need:

  • A computer with internet access
  • Basic understanding of Python programming
  • Python 3.7 or higher installed
  • Some familiarity with command-line tools

Step-by-step instructions

Step 1: Set up your development environment

Install required packages

First, we need to install the necessary Python packages for our AI chatbot. Open your terminal or command prompt and run:

pip install nltk scikit-learn flask

Why we do this: NLTK (Natural Language Toolkit) helps us process human language, scikit-learn provides machine learning tools, and Flask allows us to create a web interface for our chatbot.

Step 2: Create the basic chatbot structure

Create the main Python file

Create a new file called chatbot.py and add the following code:

import nltk
import random
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity

# Download required NLTK data
nltk.download('punkt')

# Sample training data
training_data = [
    "Hello",
    "Hi there!",
    "How are you?",
    "I'm doing well, thank you!",
    "What can you do?",
    "I can help answer questions and have conversations!",
    "Goodbye",
    "See you later!"
]

class SimpleChatbot:
    def __init__(self):
        self.vectorizer = TfidfVectorizer()
        self.vectors = None
        self.responses = []
        self.train()

    def train(self):
        # Separate questions and responses
        questions = [data for i, data in enumerate(training_data) if i % 2 == 0]
        self.responses = [data for i, data in enumerate(training_data) if i % 2 == 1]
        
        # Create TF-IDF vectors
        self.vectors = self.vectorizer.fit_transform(questions)

    def get_response(self, user_input):
        # Transform user input
        user_vector = self.vectorizer.transform([user_input])
        
        # Calculate similarity
        similarities = cosine_similarity(user_vector, self.vectors)
        
        # Find best match
        best_match_index = similarities.argmax()
        
        return self.responses[best_match_index]

# Initialize the chatbot
chatbot = SimpleChatbot()

# Simple test
print("Chatbot: Hello! I'm your AI assistant. Type 'quit' to exit.")
while True:
    user_input = input("You: ")
    if user_input.lower() in ['quit', 'exit']:
        print("Chatbot: Goodbye!")
        break
    response = chatbot.get_response(user_input)
    print(f"Chatbot: {response}")

Why we do this: This creates the basic structure of our chatbot. The chatbot learns from example conversations and tries to match new inputs to the best previous response.

Step 3: Run your basic chatbot

Execute the chatbot

Save your chatbot.py file and run it in your terminal:

python chatbot.py

Why we do this: Running the script starts your chatbot and lets you test its basic functionality.

Step 4: Enhance the chatbot with more capabilities

Add intent recognition

Update your chatbot.py file to include intent recognition:

import nltk
import random
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity

# Download required NLTK data
nltk.download('punkt')

# Define intents and responses
intents = {
    "greeting": {
        "patterns": ["hello", "hi", "hey", "greetings"],
        "responses": ["Hello! How can I help you?", "Hi there! What's up?", "Greetings! How can I assist you?"]
    },
    "goodbye": {
        "patterns": ["bye", "goodbye", "see you", "farewell"],
        "responses": ["Goodbye! Have a great day!", "See you later!", "Farewell! Come back soon!"]
    },
    "help": {
        "patterns": ["help", "what can you do", "what are you", "what is this"],
        "responses": ["I'm an AI assistant that can answer questions and have conversations!", "I can help with various topics. What do you need?", "I'm here to assist you with information and tasks!"]
    }
}

class EnhancedChatbot:
    def __init__(self):
        self.vectorizer = TfidfVectorizer()
        self.vectors = None
        self.intent_responses = {}
        self.train()

    def train(self):
        # Prepare training data
        all_patterns = []
        all_responses = []
        
        for intent, data in intents.items():
            for pattern in data["patterns"]:
                all_patterns.append(pattern)
                all_responses.append(intent)
        
        # Create TF-IDF vectors
        self.vectors = self.vectorizer.fit_transform(all_patterns)
        self.intent_responses = intents

    def get_intent(self, user_input):
        # Transform user input
        user_vector = self.vectorizer.transform([user_input])
        
        # Calculate similarity
        similarities = cosine_similarity(user_vector, self.vectors)
        
        # Find best match
        best_match_index = similarities.argmax()
        
        # Get the intent
        matched_pattern = self.vectors.get_feature_names_out()[best_match_index]
        
        return all_responses[best_match_index]

    def get_response(self, user_input):
        intent = self.get_intent(user_input)
        
        if intent in self.intent_responses:
            responses = self.intent_responses[intent]["responses"]
            return random.choice(responses)
        else:
            return "I'm not sure how to respond to that. Can you rephrase?"

# Initialize the enhanced chatbot
enhanced_chatbot = EnhancedChatbot()

# Test the enhanced chatbot
print("Enhanced Chatbot: Hello! I'm your AI assistant. Type 'quit' to exit.")
while True:
    user_input = input("You: ")
    if user_input.lower() in ['quit', 'exit']:
        print("Chatbot: Goodbye!")
        break
    response = enhanced_chatbot.get_response(user_input)
    print(f"Chatbot: {response}")

Why we do this: This enhancement allows the chatbot to recognize different types of user inputs (intents) and respond appropriately based on the intent, making it more sophisticated like the Salesforce Slackbot features.

Step 5: Add a web interface

Create a simple web interface

Create a new file called web_interface.py:

from flask import Flask, render_template, request, jsonify
from chatbot import EnhancedChatbot

app = Flask(__name__)
chatbot = EnhancedChatbot()

@app.route('/')
def home():
    return render_template('index.html')

@app.route('/get_response', methods=['POST'])
def get_response():
    user_message = request.json['message']
    bot_response = chatbot.get_response(user_message)
    return jsonify({'response': bot_response})

if __name__ == '__main__':
    app.run(debug=True)

Why we do this: Creating a web interface makes your chatbot accessible through a browser, similar to how Slackbot works in web applications.

Step 6: Create HTML template

Create the web interface template

Create a folder called templates and inside it create index.html:

<!DOCTYPE html>
<html>
<head>
    <title>AI Chatbot</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; }
        #chatbox { width: 500px; height: 400px; border: 1px solid #ccc; overflow-y: scroll; padding: 10px; margin-bottom: 10px; }
        #user-input { width: 400px; padding: 5px; }
        #send-btn { padding: 5px 10px; }
        .user-message { background-color: #e0e0e0; padding: 5px; margin: 5px 0; border-radius: 5px; }
        .bot-message { background-color: #f0f0f0; padding: 5px; margin: 5px 0; border-radius: 5px; }
    </style>
</head>
<body>
    <h1>AI Chatbot</h1>
    <div id="chatbox"></div>
    <input type="text" id="user-input" placeholder="Type your message here...">
    <button id="send-btn" onclick="sendMessage()">Send</button>

    <script>
        function sendMessage() {
            const input = document.getElementById('user-input');
            const message = input.value;
            
            if (message.trim() === '') return;
            
            // Display user message
            displayMessage(message, 'user');
            input.value = '';
            
            // Send to backend
            fetch('/get_response', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({message: message})
            })
            .then(response => response.json())
            .then(data => {
                displayMessage(data.response, 'bot');
            });
        }
        
        function displayMessage(message, sender) {
            const chatbox = document.getElementById('chatbox');
            const messageElement = document.createElement('div');
            messageElement.className = sender + '-message';
            messageElement.textContent = message;
            chatbox.appendChild(messageElement);
            chatbox.scrollTop = chatbox.scrollHeight;
        }
        
        // Allow sending with Enter key
        document.getElementById('user-input').addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                sendMessage();
            }
        });
    </script>
</body>
</html>

Why we do this: This creates a user-friendly web interface for your chatbot, making it accessible through a browser window just like Slackbot.

Step 7: Run the complete application

Start the web application

Save all files and run the web interface:

python web_interface.py

Then open your browser and go to http://localhost:5000. You should see your chatbot interface.

Why we do this: This final step combines all our components into a complete, working chatbot application that you can interact with through a web browser.

Summary

In this tutorial, you've learned how to create a basic AI chatbot similar to the capabilities mentioned in the Salesforce Slackbot update. You've built a system that can understand user intents, respond appropriately, and provide a web interface for interaction. This demonstrates core concepts of natural language processing and AI assistant development that are foundational to the advanced AI features being implemented in platforms like Slackbot.

While this is a simplified example, it shows the fundamental building blocks of modern AI assistants. Real-world implementations like Salesforce's Slackbot would include more sophisticated features like meeting transcription, desktop monitoring, and task execution, but this tutorial gives you the foundation to understand how such systems work.

Source: TNW Neural

Related Articles