Ai Coding Tools

How to Build a Simple AI Chatbot in Under 2 Hours Using OpenAI

By BTW Team4 min read

How to Build a Simple AI Chatbot in Under 2 Hours Using OpenAI

If you've ever wanted to integrate an AI chatbot into your project but felt overwhelmed by the technical details, you're not alone. Many indie hackers and solo founders face this hurdle. The good news? Building a simple AI chatbot using OpenAI can be done in under 2 hours, even if you're a beginner. In this guide, I’ll walk you through the process step-by-step, highlighting the tools you'll need, the costs involved, and some real-world insights from our own experience.

Prerequisites: What You Need Before You Start

Before diving in, make sure you have the following:

  1. An OpenAI Account: You'll need access to the OpenAI API. Sign up at OpenAI if you haven't already.
  2. Basic Understanding of JavaScript: This guide will use a simple JavaScript framework to interact with the API.
  3. Node.js Installed: If you don’t have Node.js, download and install it from Node.js.

Step 1: Setting Up Your Environment (30 minutes)

  1. Create a New Project Folder: Open your terminal and create a new directory for your chatbot project.

    mkdir ai-chatbot
    cd ai-chatbot
    
  2. Initialize a Node.js Project: Run the following command to create a package.json file.

    npm init -y
    
  3. Install Required Packages: You'll need the Axios package to make HTTP requests.

    npm install axios dotenv
    
  4. Create a .env File: This file will store your API key securely. Create a .env file and add your OpenAI API key.

    OPENAI_API_KEY=your_api_key_here
    

Step 2: Building the Chatbot Logic (30 minutes)

  1. Create an index.js File: This will be your main file where you write the chatbot logic.

  2. Add the Following Code:

    require('dotenv').config();
    const axios = require('axios');
    
    const getChatbotResponse = async (userInput) => {
        try {
            const response = await axios.post('https://api.openai.com/v1/engines/davinci-codex/completions', {
                prompt: userInput,
                max_tokens: 150,
            }, {
                headers: {
                    'Authorization': `Bearer ${process.env.OPENAI_API_KEY}`,
                    'Content-Type': 'application/json',
                },
            });
            return response.data.choices[0].text.trim();
        } catch (error) {
            console.error('Error fetching response:', error);
            return "Sorry, I couldn't process that.";
        }
    };
    
    const startChat = async () => {
        const userInput = "Hello, how can I assist you today?";
        const botResponse = await getChatbotResponse(userInput);
        console.log("Bot:", botResponse);
    };
    
    startChat();
    
  3. Run Your Chatbot: In your terminal, run:

    node index.js
    

    You should see a response from the chatbot in your console.

Step 3: Building a Simple Frontend (30 minutes)

  1. Create an index.html File: This will be the interface users interact with.

  2. Add Basic HTML Structure:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>AI Chatbot</title>
    </head>
    <body>
        <h1>AI Chatbot</h1>
        <div id="chat"></div>
        <input id="user-input" type="text" placeholder="Type your message..."/>
        <button id="send-btn">Send</button>
        <script src="script.js"></script>
    </body>
    </html>
    
  3. Create a script.js File: This file will handle user input and display responses.

  4. Add the Following Code:

    document.getElementById('send-btn').addEventListener('click', async () => {
        const userInput = document.getElementById('user-input').value;
        const response = await fetch('YOUR_BACKEND_API_ENDPOINT', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ userInput }),
        });
        const data = await response.json();
        document.getElementById('chat').innerHTML += `<p>User: ${userInput}</p><p>Bot: ${data.botResponse}</p>`;
        document.getElementById('user-input').value = '';
    });
    

Step 4: Deploying Your Chatbot (30 minutes)

  1. Choose a Hosting Service: Platforms like Vercel or Netlify are great for hosting simple web projects for free.

  2. Deploy Your Project: Follow the instructions on the chosen platform to deploy your chatbot. You’ll need to point it to your GitHub repository if you’re using one.

Troubleshooting: What Could Go Wrong

  • API Key Issues: Make sure your OpenAI API key is correct and has permissions.
  • CORS Errors: If you encounter CORS issues, ensure your backend is set up to allow requests from your frontend.
  • Response Format: Ensure that the response from OpenAI is being parsed correctly.

What's Next: Enhancing Your Chatbot

Once you have the basics down, consider adding features like:

  • User Authentication: To keep track of user interactions.
  • Persistent Conversations: Store chat history in a database.
  • Advanced NLP Capabilities: Use different OpenAI models for improved responses.

Conclusion: Start Here

Building a simple AI chatbot using OpenAI is not only achievable in under 2 hours but also a great way to learn about integrating AI into your projects. Start by following the steps above, and don’t hesitate to iterate on your chatbot as you gather user feedback.

Pricing Breakdown

  • OpenAI API: Pricing starts at $0 for limited usage, then scales based on usage (typically $0.006 per token).
  • Hosting: Free options available on Vercel/Netlify; expect to pay if you need more resources.

In our experience, using OpenAI has been straightforward and effective for basic chatbot functionality. However, keep in mind that costs can add up with increased usage, so monitor your API usage closely.

Follow Our Building Journey

Weekly podcast episodes on tools we're testing, products we're shipping, and lessons from building in public.

Subscribe

Never miss an episode

Subscribe to Built This Week for weekly insights on AI tools, product building, and startup lessons from Ryz Labs.

Subscribe
Ai Coding Tools

Why AI Coding Tools Are Overrated for Elite Developers

Why AI Coding Tools Are Overrated for Elite Developers As we dive into 2026, the hype surrounding AI coding tools continues to grow. On Twitter, you’ll see countless tweets celebra

May 8, 20264 min read
Ai Coding Tools

How to Build an AI-Powered Personal Assistant in Under 2 Hours

How to Build an AIPowered Personal Assistant in Under 2 Hours If you're like most indie hackers, you probably have a million things on your plate. Wouldn’t it be great if you could

May 8, 20264 min read
Ai Coding Tools

The 3 Most Common Mistakes When Using AI Coding Tools

The 3 Most Common Mistakes When Using AI Coding Tools As a solo founder or indie hacker, diving into AI coding tools can feel like finding a cheat code for building projects faster

May 8, 20264 min read
Ai Coding Tools

How to Develop an AI-Based Application in Just 2 Weeks

How to Develop an AIBased Application in Just 2 Weeks Building an AIbased application sounds daunting, right? But what if I told you that with the right tools and a focused approac

May 8, 20265 min read
Ai Coding Tools

How to Improve Your Coding Skills with AI Tools in 2 Weeks

How to Improve Your Coding Skills with AI Tools in 2 Weeks If you’re like me, you’ve probably hit a wall in your coding journey at some point. You might be wondering, “How can I le

May 8, 20265 min read
Ai Coding Tools

Cursor vs GitHub Copilot: Which One Enhances Coding Productivity in 2026?

Cursor vs GitHub Copilot: Which One Enhances Coding Productivity in 2026? If you’re a solo founder or indie hacker trying to juggle multiple projects, you know that coding can quic

May 8, 20264 min read