Skip to content
Youths Forum Youths Forum Youths Forum

Tech Blogs & Programming Tutorials

Youths Forum Youths Forum Youths Forum

Tech Blogs & Programming Tutorials

  • Blog
  • News
  • Programming
    • PHP
    • JavaScript
    • JQuery
    • CSS
    • HTML
    • API
  • Stock Market Live
  • Automobiles
    • Cars
  • Gadgets
    • Phones
    • Android Phones

Categories

  • Automobiles (12)
    • Cars (7)
  • Blog (103)
    • Poems (2)
    • Space (2)
  • Command (2)
  • Education (2)
  • Entertainment (4)
  • Gadgets (9)
    • Phones (8)
      • Android Phones (4)
  • HTML Templates (11)
  • IT Training Institutes (1)
  • Lifestyle (4)
  • News (51)
  • Others (23)
  • Programming (296)
    • API (16)
    • CSS (83)
    • Database (4)
    • Hosting (1)
    • HTML (37)
    • JavaScript (117)
      • JQuery (27)
      • ReactJS (7)
    • PHP (116)
  • Python (3)
  • recipes (1)
  • SEE Result (1)
  • Server (3)
  • Blog
  • News
  • Programming
    • PHP
    • JavaScript
    • JQuery
    • CSS
    • HTML
    • API
  • Stock Market Live
  • Automobiles
    • Cars
  • Gadgets
    • Phones
    • Android Phones
Close

Search

JavaScriptJQueryProgramming

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

By Admin
December 26, 2024 4 Min Read
0

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 :

https://www.youtube.com/watch?v=gSIg0pHxm88

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.

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.

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

Tags:

aichatbotgemini
Author

Admin

Follow Me
Other Articles
Previous

Analyze Your Website’s Traffic with Google Analytics

Next

Building a Voice-Controlled YouTube Video Player with JavaScript

No Comment! Be the first one.

Leave a Reply

Your email address will not be published. Required fields are marked *

FIFA World Cup 2026 Predict and Win by SportsGuff

Recent Posts

  • Unpacking Nepal’s Record Rs 2.12 Trillion Budget and What It Means for You
  • How to Write a Strong Scholarship Application: The Ultimate Step-by-Step Guide
  • How to Prepare for Exams Without Stress: The Ultimate Science-Backed Guide
  • Chiranjibi Adhikari Appointed Acting President of CAN Federation
  • How to Design a Student Marksheet Using HTML and CSS

Tags

adsense ai animate animation animation using HTML and CSS API blog calculator chatgpt Cryptocurrency CSS css animation design Email Facebook featured filemanager file manager free template google htaccess HTML image Instagram interview javascript JQuery jquery ui NADA AutoShow NADA Auto Show 2024 password PHP Progressive Web App PWA QR random react reactjs Rotate travel Twitter vpn youthforum youthsforum youtube

About Us

At Youths Forum, we are passionate about sharing knowledge that empowers students, educators, professionals, and technology enthusiasts.

Our Mission

Our mission is simple: to make technology and education accessible, understandable, and beneficial for everyone. We strive to create content that helps our readers learn new skills and stay updated with industry developments.

RSS RSS

  • Unpacking Nepal’s Record Rs 2.12 Trillion Budget and What It Means for You Admin
  • How to Write a Strong Scholarship Application: The Ultimate Step-by-Step Guide Admin
  • How to Prepare for Exams Without Stress: The Ultimate Science-Backed Guide Admin

Quick Links

  • Stock Market Live
  • Parliament Election 2082
Copyright 2026 — Youths Forum. All rights reserved. Blogsy WordPress Theme