DEV Community

Venkatesh Jonnagadla
Venkatesh Jonnagadla

Posted on Edited on

Google AI Chatbot

1/ Install Visual Studio Code
2/ Install Python and get the path where python is installed
C:\Users\XXXXX\Python\pythoncore-3.15-64\python.exe
python --version
python path

3/ go to aistudio.google.com and use 300$ free credit. Create API Key
4/ Check the doumentation for api-key usage according to the requirement. In my case I am using Python. So, I refer the python code
5/ Create a workspace folder on your desktop and open using VS Code editor. Then open the terminal in the path using view --> Open terminal
6/ Create environment in the path for python using below command
python -m venv myEnv
7/ Activate virtual environment
cd .\myEnv\Scripts
.\Activate.ps1
if security error occur then
Set-ExecutionPolicy -Scope CurrentUser RemoteSigned
once activated, it shows (yourenv) in greencolor
8/ From the command prompt go to the directory where Pythoncode is writted, same place install flask
pip install Flask
pip list --> will show if installed or not
pip install google-generativeai
9/ Now in the workspace folder create one more folder called templates
10/ In the templates folder create

Welcome.html (UnFormatted output)


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Venkatesh AI Chatbot</title>

    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">

    <style>
        body {
            background-color: #f4f6f9;
        }

        .chat-container {
            max-width: 900px;
            margin: 30px auto;
        }

        .chat-header {
            background: #8e95a0;
            color: white;
            padding: 15px;
            border-radius: 10px 10px 0 0;
            font-size: 24px;
            font-weight: bold;
            text-align: center;
        }

        .chat-window {
            height: 500px;
            overflow-y: auto;
            background: white;
            border: 1px solid #dee2e6;
            padding: 15px;
        }

        .message {
            margin-bottom: 12px;
            padding: 10px 15px;
            border-radius: 10px;
            max-width: 80%;
            word-wrap: break-word;
            clear: both;
        }

        .user-message {
            background-color: #d1e7dd;
            float: right;
        }

        .bot-message {
            background-color: #e9ecef;
            float: left;
        }

        .input-section {
            border: 1px solid #dee2e6;
            border-top: none;
            padding: 15px;
            background: white;
            border-radius: 0 0 10px 10px;
        }

        textarea {
            resize: none;
        }

        .typing {
            font-style: italic;
            color: gray;
        }
    </style>
</head>
<body>

<div class="container chat-container">

    <!-- Header -->
    <div class="chat-header">
        Venkatesh AI Chatbot
    </div>

    <!-- Chat Window -->
    <div id="chatWindow" class="chat-window">
        <div class="message bot-message">
            Hello! How can I help you today?
        </div>
        <div style="clear:both;"></div>
    </div>

    <!-- Input Area -->
    <div class="input-section">
        <div class="row">
            <div class="col-md-10">
                <textarea
                    id="userInput"
                    class="form-control"
                    rows="3"
                    placeholder="Type your message here..."></textarea>
            </div>

            <div class="col-md-2 d-grid">
                <button id="sendBtn" class="btn btn-primary">
                    Send
                </button>
            </div>
        </div>
    </div>

</div>

<!-- JQuery -->
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>

<!-- Bootstrap JS -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>

<script>

function appendMessage(message, type)
{
    let cssClass = (type === "user")
        ? "user-message"
        : "bot-message";

    $("#chatWindow").append(`
        <div class="message ${cssClass}">
            ${message}
        </div>
        <div style="clear:both;"></div>
    `);

    scrollToBottom();
}

function scrollToBottom()
{
    $("#chatWindow").scrollTop(
        $("#chatWindow")[0].scrollHeight
    );
}

$("#sendBtn").on("click", function ()
{
    sendMessage();
});

$("#userInput").on("keypress", function(e)
{
    if(e.which === 13 && !e.shiftKey)
    {
        e.preventDefault();
        sendMessage();
    }
});

function sendMessage()
{
    let userText = $("#userInput").val().trim();

    if(userText === "")
        return;

    // Append User Message
    appendMessage(userText, "user");

    // Clear input
    $("#userInput").val("");

    // Show typing indicator
    let typingId = "typing_" + Date.now();

    $("#chatWindow").append(`
        <div id="${typingId}" class="message bot-message typing">
            AI is typing...
        </div>
        <div style="clear:both;"></div>
    `);

    scrollToBottom();

    // AJAX POST Call
    $.ajax({
       //url: "http://127.0.0.1:5000/chat",
        url: "/chat",
        type: "POST",
        contentType: "application/json",
        data: JSON.stringify({
            message: userText
        }),

        success: function(response)
        {
            $("#" + typingId).remove();

            appendMessage(
                response.response || "No response received",
                "bot"
            );
        },

        error: function(xhr)
        {
            $("#" + typingId).remove();

            console.log(xhr.responseText);

            appendMessage(
                "Error: " + xhr.responseText,
                "bot"
            );
        }
    });
}

</script>

</body>
</html>
Enter fullscreen mode Exit fullscreen mode

11/ In the workspace folder create Welcome.py

from flask import Flask, render_template, request, jsonify
import google.generativeai as genai
import os

# Replace with your actual Gemini API key
GOOGLE_API_KEY = "your_APIKe"

genai.configure(api_key=GOOGLE_API_KEY)
#for m in genai.list_models():
   # print(m.name)

#model = genai.GenerativeModel("gemini-1.5-flash")
model = genai.GenerativeModel("gemini-3.5-flash-lite")
chat = model.start_chat(history=[])

app = Flask(__name__)

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

@app.route('/chat', methods=['POST'])
def chat_response():
    user_input = request.json.get('message')

    if not user_input:
        return jsonify({"error": "No message provided"}), 400

    try:
        response_raw = chat.send_message(user_input)

        #print(response_raw)
        print("RAW:", response_raw)

        response = response_raw.text
        print("TEXT:", response)

        return jsonify({"response": response})

    except Exception as e:
        print(f"Error: {e}")
        return jsonify({"error": str(e)}), 500

if __name__ == '__main__':
    app.run(debug=True)
Enter fullscreen mode Exit fullscreen mode

12/ Dubug the output and open the chatbot in Chrome and test

Alternative Design

Welcome.html (Formatted Output)


<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Chat</title>
  <link rel="stylesheet"
        href="https://cdn.jsdelivr.net/npm/highlight.js@11.9.0/styles/github-dark.min.css">
  <style>
    body { font-family: system-ui, sans-serif; background:#f7f7f8; margin:0; padding:20px; }
    #chat-box { max-width: 800px; margin: auto; }
    .msg { padding: 12px 16px; margin: 10px 0; border-radius: 10px; line-height: 1.6; }
    .user { background:#2563eb; color:white; text-align:right; }
    .bot  { background:#ffffff; border:1px solid #e5e7eb; }
    .bot pre {
      background:#1e1e1e; color:#eee; padding:12px; border-radius:8px;
      overflow-x:auto; position:relative;
    }
    .bot code:not(pre code) {
      background:#f1f5f9; padding:2px 6px; border-radius:4px;
      font-family: 'Fira Code', monospace; font-size: 0.9em;
    }
    .bot h1,.bot h2,.bot h3 { margin-top: 10px; }
    .bot ul, .bot ol { padding-left: 22px; }
    .bot table { border-collapse: collapse; margin: 8px 0; }
    .bot th, .bot td { border:1px solid #ddd; padding:6px 10px; }
    #input-area { max-width:800px; margin:20px auto; display:flex; gap:8px; }
    #msg { flex:1; padding:10px; border-radius:8px; border:1px solid #ccc; }
    button { padding:10px 18px; border:none; background:#2563eb; color:#fff;
             border-radius:8px; cursor:pointer; }
  </style>
</head>
<body>
  <div id="chat-box"></div>
  <div id="input-area">
    <input id="msg" placeholder="Ask anything..." onkeydown="if(event.key==='Enter')send()">
    <button onclick="send()">Send</button>
  </div>

  <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/highlight.js@11.9.0/lib/highlight.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/dompurify@3.0.6/dist/purify.min.js"></script>

  <script>
    // Configure marked to use highlight.js
    marked.setOptions({
      highlight: function(code, lang) {
        if (lang && hljs.getLanguage(lang)) {
          try { return hljs.highlight(code, {language: lang}).value; }
          catch (e) {}
        }
        return hljs.highlightAuto(code).value;
      },
      breaks: true,      // turn \n into <br>
      gfm: true          // GitHub-flavored markdown (tables, etc.)
    });

    const chatBox = document.getElementById('chat-box');

    function addMessage(role, text) {
      const div = document.createElement('div');
      div.className = 'msg ' + role;
      if (role === 'bot') {
        // Render markdown safely
        const rawHtml = marked.parse(text);
        div.innerHTML = DOMPurify.sanitize(rawHtml);
      } else {
        div.textContent = text;
      }
      chatBox.appendChild(div);
      window.scrollTo(0, document.body.scrollHeight);
      return div;
    }

    async function send() {
      const input = document.getElementById('msg');
      const text = input.value.trim();
      if (!text) return;
      input.value = '';

      addMessage('user', text);
      const botDiv = addMessage('bot', '_thinking..._');

      try {
        const res = await fetch('/chat', {
          method: 'POST',
          headers: {'Content-Type': 'application/json'},
          body: JSON.stringify({message: text})
        });
        const data = await res.json();
        if (data.error) {
          botDiv.textContent = 'Error: ' + data.error;
        } else {
          const html = marked.parse(data.response);
          botDiv.innerHTML = DOMPurify.sanitize(html);
        }
      } catch (e) {
        botDiv.textContent = 'Network error: ' + e;
      }
    }
  </script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Welcome.py

from flask import Flask, render_template, request, jsonify
import google.generativeai as genai
import os

# Replace with your actual Gemini API key
GOOGLE_API_KEY = "YourGoogleAPIKEY"

genai.configure(api_key=GOOGLE_API_KEY)
#for m in genai.list_models():
   # print(m.name)

#model = genai.GenerativeModel("gemini-1.5-flash")
model = genai.GenerativeModel("gemini-3.5-flash-lite")
chat = model.start_chat(history=[])

app = Flask(__name__)

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

@app.route('/chat', methods=['POST'])
def chat_response():
    user_input = request.json.get('message')
    if not user_input:
        return jsonify({"error": "No message provided"}), 400
    try:
        response_raw = chat.send_message(user_input)
        response = response_raw.text  # markdown text
        return jsonify({"response": response})
    except Exception as e:
        print(f"Error: {e}")
        return jsonify({"error": str(e)}), 500

if __name__ == '__main__':
    app.run(debug=True)
Enter fullscreen mode Exit fullscreen mode

I have given both ways the 2nd one gives more formatted output like DeepSeek, ChatGpt. Try yourself!!!

All the best!!!!!!!!!!!!!!!!!!!!!!!!

Top comments (0)