S9.10

    How to Build a Chatbot for Your Website

    ·
    How to Build a Chatbot for Your Website

    The short answer

    To build a chatbot for your website, you need a chat UI that captures messages, a backend route that calls an LLM API, and a way to pass conversation history so the model remembers what was said. That's the core. Add a knowledge base with RAG if you want it to answer questions about your products or content.

    TL;DR

    • →A website chatbot needs three parts: a chat UI, a backend API route, and an LLM connection.
    • →You can build a working chatbot in a weekend with React and the Claude or OpenAI API.
    • →Context management is the key challenge. You need to decide how much history to send each turn.
    • →Add a knowledge base with RAG to make your chatbot answer questions from your own content.
    • →A well-configured chatbot reduces support volume by 30-40% for most businesses.

    How do you build a chatbot for your website?

    To build a chatbot for your website, you need a chat UI that captures messages, a backend route that calls an LLM API, and a way to pass conversation history so the model remembers what was said. That's the core. Add a knowledge base with RAG if you want it to answer questions about your products or content.

    This guide covers a custom build. If you want something deployed in an afternoon, tools like Intercom or Crisp have AI features built in. But if you need customisation or system integration, build it yourself.

    Step 1: Build the chat UI

    A minimal chat UI needs three things.

    • A message list that shows the conversation.
    • An input field for the user to type.
    • A way to show loading state while the model responds.

    In React:

    const [messages, setMessages] = useState<Message[]>([]);
    const [input, setInput] = useState("");
    const [loading, setLoading] = useState(false);
     
    async function sendMessage() {
      const userMessage = { role: "user", content: input };
      setMessages(prev => [...prev, userMessage]);
      setInput("");
      setLoading(true);
      
      const response = await fetch("/api/chat", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ messages: [...messages, userMessage] })
      });
      
      const data = await response.json();
      setMessages(prev => [...prev, { role: "assistant", content: data.reply }]);
      setLoading(false);
    }

    Keep it simple. You can add streaming later for a better user experience.

    Step 2: Build the backend API route

    Your backend receives the message history and calls the LLM.

    from flask import Flask, request, jsonify
    import anthropic
     
    app = Flask(__name__)
    client = anthropic.Anthropic()
     
    SYSTEM_PROMPT = """You are a helpful assistant for [Your Company].
    You answer questions about our products and services.
    If you don't know the answer, say so and offer to connect the user with a human."""
     
    @app.route("/api/chat", methods=["POST"])
    def chat():
        data = request.json
        messages = data.get("messages", [])
        
        response = client.messages.create(
            model="claude-3-5-haiku-20241022",
            max_tokens=500,
            system=SYSTEM_PROMPT,
            messages=messages
        )
        
        return jsonify({"reply": response.content[0].text})

    Step 3: Manage conversation context

    Here's the bit that matters most. Every turn, you send the full conversation history. That means token costs compound as conversations get longer.

    Set a limit. Keep the last 10-20 messages. Or summarise older messages and prepend the summary.

    def trim_messages(messages, max_messages=20):
        if len(messages) <= max_messages:
            return messages
        # Keep system context + recent messages
        return messages[-max_messages:]

    Don't skip this. A user who chats for 30 minutes can accumulate thousands of tokens of history. That's real cost.

    Step 4: Add a knowledge base with RAG

    A general chatbot answers general questions. A useful chatbot answers questions about your business.

    Index your FAQs, product docs, and support articles. On each query, retrieve the relevant sections and add them to the system prompt. The model answers from your content, not from guesswork.

    def get_context(user_question: str) -> str:
        relevant_docs = vector_store.search(user_question, top_k=3)
        return "\n\n".join(relevant_docs)
     
    # In your chat handler
    context = get_context(user_question)
    system_with_context = SYSTEM_PROMPT + f"\n\nRelevant information:\n{context}"

    See how to build a RAG app for the full setup.

    Step 5: Handle handoff to humans

    Not every question should be answered by AI. Set clear criteria: billing disputes, complaints, or requests that need account access should go to a human.

    Add a tool or a trigger phrase that routes to your support channel. In most systems, that's a CRM ticket or a Slack alert.

    For chatbots that need to connect to CRM systems and automate follow-up workflows, Njin handles the automation layer. For a fully custom build, Devwiz can build the whole thing.


    Want a chatbot built for your website that actually converts? Let's talk about what you need.

    Frequently Asked Questions

    Should I build a chatbot or use an off-the-shelf tool like Intercom?
    Off-the-shelf tools are faster to deploy and handle hosting, analytics, and handoff to human agents. Build your own when you need deep customisation, want full data control, or need the chatbot to integrate tightly with your systems. Custom builds cost more upfront but give you complete flexibility.
    How do I make the chatbot answer questions about my business?
    Use RAG. Index your product docs, FAQs, and support articles as embeddings in a vector database. When a user asks a question, retrieve the relevant docs and pass them to the model as context. The model answers using your content, not general training data.
    How do I handle the chatbot giving wrong answers?
    Three approaches: constrain the system prompt to only answer questions it has context for, add a confidence check step, or give users an easy path to a human. Most production chatbots use a combination. Don't promise accuracy you can't deliver.