Building Your Own Chatbot with Gemini API: A Step-by-Step Guide

0
66

In the fast-paced world of artificial intelligence, chatbots have become indispensable tools for businesses, educators, and tech enthusiasts. Whether it’s for customer support, answering frequently asked questions, or just having an engaging AI companion, chatbots can significantly enhance user interaction. With Google’s Gemini API, creating your own chatbot is now easier than ever. In this article, we’ll guide you through the process of building a functional chatbot using Bootstrap, jQuery, and the Gemini API.

Why Gemini API?

Gemini API, powered by Google’s advanced AI models, offers robust natural language understanding and response generation capabilities. It’s flexible, developer-friendly, and can be easily integrated into web applications. Whether you’re a developer experimenting with AI or a business aiming to automate customer interactions, Gemini API provides a powerful foundation.

Follow this video for complete guidance :

The Tools You’ll Need

To build your chatbot, we’ll use:

  • HTML5: For structuring the chatbot interface.
  • CSS & Bootstrap: For styling and ensuring a responsive design.
  • JavaScript & jQuery: For handling user interactions and API calls.
  • Gemini API: For generating dynamic AI responses.

These technologies ensure our chatbot is not only functional but also visually appealing and responsive on all devices.

Full Source Code

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Gemini Chatbot</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
    <style>
        body {
            background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
            min-height: 100vh;
        }
        .container {
            max-width: 800px;
        }
        .chat-container {
            background: rgba(255, 255, 255, 0.95);
            border-radius: 20px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
            padding: 20px;
            margin-top: 2rem;
        }
        .chat-header {
            padding: 15px 0;
            border-bottom: 2px solid #eee;
            margin-bottom: 20px;
        }
        .chat-header h2 {
            background: linear-gradient(45deg, #2193b0, #6dd5ed);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            font-weight: bold;
        }
        #chatbox {
            height: 50vh;
            overflow-y: scroll;
            padding: 20px;
            scrollbar-width: thin;
            scrollbar-color: #6dd5ed transparent;
        }
        #chatbox::-webkit-scrollbar {
            width: 6px;
        }
        #chatbox::-webkit-scrollbar-thumb {
            background-color: #6dd5ed;
            border-radius: 3px;
        }
        .message {
            margin: 15px 0;
            padding: 12px 18px;
            border-radius: 15px;
            max-width: 80%;
            position: relative;
            animation: fadeIn 0.3s ease-in;
        }
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }
        .text-end .message {
            background: linear-gradient(45deg, #2193b0, #6dd5ed);
            color: white;
            margin-left: auto;
            border-bottom-right-radius: 5px;
        }
        .text-start .message {
            background: #f0f2f5;
            color: #1a1a1a;
            border-bottom-left-radius: 5px;
        }
        .input-group {
            margin-top: 20px;
            background: white;
            padding: 15px;
            border-radius: 15px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.05);
        }
        #userInput {
            border: none;
            padding: 10px 15px;
            border-radius: 10px;
            background: #f0f2f5;
        }
        #userInput:focus {
            outline: none;
            box-shadow: 0 0 0 2px #6dd5ed;
        }
        #sendBtn {
            background: linear-gradient(45deg, #2193b0, #6dd5ed);
            border: none;
            padding: 10px 25px;
            border-radius: 10px;
            margin-left: 10px;
            transition: transform 0.2s;
        }
        #sendBtn:hover {
            transform: translateY(-2px);
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="chat-container">
            <div class="chat-header">
                <h2 class="text-center">Gemini AI Assistant</h2>
            </div>
            <div id="chatbox">
                <!-- Messages will appear here -->
            </div>
            <div class="input-group">
                <input type="text" id="userInput" class="form-control" placeholder="Type your message...">
                <button id="sendBtn" class="btn btn-primary">Send</button>
            </div>
        </div>
    </div>
    <script>
        const API_KEY = 'AIzaSyB-tI5qAO-zEHDzAKH5VtuU7cpUmsr_yF0';
        const API_URL = 'https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateContent';
        
        $(document).ready(function() {
            function appendMessage(text, isUser) {
                const alignment = isUser ? 'text-end' : 'text-start';
                const sender = isUser ? 'You' : 'Bot';
                $('#chatbox').append(`
                    <div class="${alignment}">
                        <div class="message">${text}</div>
                    </div>
                `);
                $('#chatbox').scrollTop($('#chatbox')[0].scrollHeight);
            }

            $('#sendBtn').click(async function() {
                let userMessage = $('#userInput').val().trim();
                if (!userMessage) return;
                
                appendMessage(userMessage, true);
                $('#userInput').val('').prop('disabled', true);
                $('#sendBtn').prop('disabled', true);

                try {
                    const response = await $.ajax({
                        url: `${API_URL}?key=${API_KEY}`,
                        method: 'POST',
                        contentType: 'application/json',
                        data: JSON.stringify({
                            contents: [{ parts: [{ text: userMessage }] }]
                        })
                    });
                    
                    const botResponse = response?.candidates?.[0]?.content?.parts?.[0]?.text || "No response from Gemini.";
                    appendMessage(botResponse, false);
                } catch (error) {
                    appendMessage("Failed to get a response.", false);
                } finally {
                    $('#userInput').prop('disabled', false).focus();
                    $('#sendBtn').prop('disabled', false);
                }
            });

            $('#userInput').keypress(function(e) {
                if (e.which === 13) {
                    $('#sendBtn').click();
                }
            });
        });
    </script>
</body>
</html>

Getting Started with Gemini API

To use the Gemini API, you need an API key. Here’s how you can obtain it:

  • Create an API key from here : https://aistudio.google.com/
  • Keep your API key secure and do not expose it in client-side code for production environments.
ALSO READ  Free Personality Check with DOB using JavaScript in 5 minutes

Structuring the Chatbot Interface

The chatbot interface is designed to be user-friendly. A clean input box allows users to type their messages, while a scrollable chat window displays both user and AI responses in real-time. Bootstrap helps in creating a sleek and responsive design, while jQuery streamlines the interaction between the user interface and the backend API.

How the Chatbot Works

  • User Input: The user types a message in the input field and clicks ‘Send.’
  • API Call: A JavaScript function sends the user’s message to the Gemini API using an AJAX request.
  • AI Response: The API processes the input and returns a dynamic AI-generated response.
  • Display Response: Both user and AI messages are displayed in the chatbox in an organized and visually appealing format.

Best Practices for API Integration

  • Always validate user input before sending it to the API.
  • Use backend services to securely handle API keys.
  • Implement error handling to manage API failures gracefully.
  • Optimize chat performance to ensure smooth interaction.

Enhancing Your Chatbot

Once your chatbot is functional, you can enhance it further:

  • Add typing indicators to show when the AI is processing a response.
  • Implement session management to maintain context in longer conversations.
  • Integrate voice input/output for a hands-free experience.
  • Customize the chatbot’s personality to align with your brand.

Deployment and Hosting

When you’re satisfied with your chatbot, deploy it on a hosting platform like Netlify, Vercel, or AWS. Make sure to use environment variables for your API key to ensure security.

Building a chatbot with Gemini API is a rewarding project that combines frontend development, API integration, and artificial intelligence. With tools like Bootstrap and jQuery, you can create a responsive and interactive chatbot interface that caters to your specific needs. Whether you’re developing it for a business application or personal use, the possibilities are endless.

ALSO READ  Create Sticky Notes Application using HTML, CSS and JavaScript in 5 minutes

Start experimenting with your chatbot today and explore the limitless potential of AI-powered conversations!

Comments are closed.