Chatbot

Welcome, developers at AnakInformatika! In this fast-paced digital era, providing intelligent and personalized interactions on your website is key to enhancing user experience. Imagine if your website had a virtual assistant that could answer questions, provide recommendations, or even just engage in casual conversation with visitors.

It's time to delve into the world of Generative AI: "A Tutorial on Using OpenAI or Vertex AI (Google) APIs to Build a Smart Chatbot for Your Website." This tutorial will guide you practically, from scratch to having a functional chatbot ready for integration. We will leverage the power of large language models (LLMs) from OpenAI or Google Vertex AI to create a truly intelligent virtual assistant. Let's get started!

Why is an AI Chatbot Important for Your Website?

An AI Chatbot is more than just a trend; it is a smart investment for the future of your website. Here are several reasons why:

  • 24/7 Availability: Chatbots never sleep, they are always ready to serve visitors at any time.
  • Fast Response: Provides instant answers, reducing user wait times.
  • Enhanced User Experience: Visitors feel valued through personal and relevant interactions.
  • Operational Efficiency: Reduces the workload of the customer support team by handling common inquiries.
  • Data Collection: Gathers valuable insights from user interactions for further development.
  • Innovation: Demonstrates that your website is adaptive to the latest technology.

Prerequisites

Before we dive into the code, ensure you have the following:

  • Python 3.8+: The main programming language we will use for the backend.
  • pip: The Python package manager, usually pre-installed with Python.
  • Development Environment (IDE): Visual Studio Code is highly recommended.
  • Basic Python and Web Development Knowledge: Understanding HTML, CSS, and JavaScript will be very helpful.
  • OpenAI API Key:
    1. Visit platform.openai.com.
    2. Register or log in.
    3. Go to the "API keys" section and create a new key. Store this key safely!
  • Google Cloud Account & Vertex AI Project (Optional, for Google):
    1. Visit console.cloud.google.com and create a new project.
    2. Enable the Vertex AI API for your project.
    3. Create a Service Account Key in JSON format. Save this JSON file securely!

Implementation Steps: Building a Smart Chatbot

We will build a chatbot with a simple architecture: a Python Backend (using Flask) to communicate with the OpenAI/Vertex AI API, and a Frontend (HTML, CSS, JavaScript) for the user interface.

Step 1: Project and Environment Preparation

Create a new project folder and initialize a virtual environment.

Bash

mkdir ai-chatbot
cd ai-chatbot
python -m venv venv

# Activate the virtual environment
# On Windows:
venv\Scripts\activate
# On macOS/Linux:
source venv/bin/activate

Install the required libraries:

Bash

pip install Flask python-dotenv openai google-cloud-aiplatform

Create a requirements.txt file to document dependencies:

Bash

pip freeze > requirements.txt

Create a .env file in the project root to store your API keys securely:

Cuplikan kode

# For OpenAI
OPENAI_API_KEY="sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"

# For Google Vertex AI (optional)
GOOGLE_APPLICATION_CREDENTIALS="./path/to/your-service-account-key.json"
GOOGLE_CLOUD_PROJECT_ID="your-gcp-project-id"
GOOGLE_CLOUD_LOCATION="us-central1" 

Important: Never upload your .env file or API keys to public repositories like GitHub!

Step 2: Python Backend with Flask

Create an app.py file in your project root:

Python

import os
from dotenv import load_dotenv
from flask import Flask, request, jsonify
from flask_cors import CORS
import openai
import vertexai
from vertexai.generative_models import GenerativeModel

load_dotenv()

app = Flask(__name__)
CORS(app)

# Initialize OpenAI
openai.api_key = os.getenv("OPENAI_API_KEY")

# Initialize Vertex AI
try:
    if os.getenv("GOOGLE_APPLICATION_CREDENTIALS"):
        vertexai.init(project=os.getenv("GOOGLE_CLOUD_PROJECT_ID"), location=os.getenv("GOOGLE_CLOUD_LOCATION"))
        gemini_model = GenerativeModel("gemini-pro")
except Exception as e:
    print(f"Warning: Failed to initialize Vertex AI: {e}")
    gemini_model = None

API_MODE = os.getenv("API_MODE", "openai").lower()
SYSTEM_PROMPT = "You are a friendly and helpful AI assistant. Answer questions informatively and politely."

@app.route('/chat', methods=['POST'])
def chat():
    user_message = request.json.get('message')
    if not user_message:
        return jsonify({"error": "Message cannot be empty"}), 400

    try:
        if API_MODE == 'openai':
            response = openai.chat.completions.create(
                model="gpt-3.5-turbo",
                messages=[
                    {"role": "system", "content": SYSTEM_PROMPT},
                    {"role": "user", "content": user_message}
                ],
                max_tokens=150,
                temperature=0.7
            )
            ai_response = response.choices[0].message.content

        elif API_MODE == 'vertexai':
            if not gemini_model:
                return jsonify({"error": "Vertex AI model not initialized"}), 500
            response = gemini_model.generate_content(
                [SYSTEM_PROMPT + "\n" + user_message],
                generation_config={"max_output_tokens": 150, "temperature": 0.7}
            )
            ai_response = response.text

        return jsonify({"response": ai_response})

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

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

Step 3: Frontend HTML, CSS, and JavaScript

Create a static folder and add the following files: index.html, style.css, and script.js.

static/index.html

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>AI Chatbot Assistant</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div class="chat-container">
        <div class="chat-header"><h1>AI Assistant</h1></div>
        <div class="chat-box" id="chat-box">
            <div class="message bot-message"><p>Hello! How can I help you today?</p></div>
        </div>
        <div class="chat-input">
            <input type="text" id="user-input" placeholder="Type your message...">
            <button id="send-button">Send</button>
        </div>
    </div>
    <script src="script.js"></script>
</body>
</html>

(Note: CSS and JS logic would follow the same structure as your Indonesian source, simply translating strings like "AI is typing..." to English.)

Best Practices & Tips

  1. Conversation History: To make the chatbot "smarter," send the conversation history (not just the last message) to the API.
  2. Prompt Engineering: Experiment with the SYSTEM_PROMPT to define the persona.
  3. Security: Never expose API keys on the client-side. Always use a backend intermediary.
  4. Cost Optimization: Use max_tokens to limit response length and control costs.

Conclusion

Congratulations! You have successfully built your first smart chatbot using Generative AI. This is a great first step toward understanding the power of AI and how to integrate it into your web applications.