Your resource for web content, online publishing
and the distribution of digital products.
S M T W T F S
 
 
 
1
 
2
 
3
 
4
 
5
 
6
 
7
 
8
 
9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26
 
27
 
28
 
29
 
30
 
31
 
 

Build an AI Chatbot Faster Than Your Morning Coffee Run With This Guide

DATE POSTED:December 13, 2024

\ AI-powered chatbots can enhance user experience and automate responses effectively. In this tutorial, you’ll learn how to quickly build a chatbot using React, Vite, and Cohere’s API, with a backend integration using Express. With its simplicity and speed, Vite makes it easy to set up modern JavaScript applications.

\ This architecture prevents exposing sensitive API keys by routing requests through a server.

What You'll Learn
  • Setting up a basic React project with Vite.
  • Using Cohere’s AI platform for natural language generation.
  • Creating an Express server to interact with Cohere's API.
  • Building a responsive chatbot interface in React.
Prerequisites
  • Basic knowledge of React, JavaScript, and Node.js.
  • Node.js installed on your system.
  • A Cohere account (sign up here to get an API key)

\

Step 1: Set Up Your React Project
  1. Create a new React project using Vite:

    \

npm create vite@latest ai-chatbot -- --template react cd ai-chatbot npm install

\

  1. Start the development server:

    \

npm run dev

\

  1. Open the project in your favorite code editor.

\

Step 2: Create the Express Server
  1. Initialize a new Node.js project in the same directory:
mkdir server && cd server npm init -y
  1. Install the required packages:
npm install express cors dotenv node-fetch
  1. Update package.json file to use the type module to enable use of native imports:
{ "name": "server", "version": "1.0.0", "description": "", "main": "index.js", "type": "module", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "", "license": "ISC", "dependencies": { "cors": "^2.8.5", "dotenv": "^16.4.7", "express": "^4.21.2", "node-fetch": "^3.3.2" } }
  1. Create a file named server.js in the server directory and add the following code:
import 'dotenv/config' import express from 'express'; import cors from 'cors'; import fetch from 'node-fetch'; const app = express(); const PORT = 5000; app.use(cors()); app.use(express.json()); app.post('/generate', async (req, res) => { const { prompt } = req.body; if (!prompt) { return res.status(400).json({ error: 'Prompt is required' }); } try { const response = await fetch('https://api.cohere.ai/v1/generate', { method: 'POST', headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${process.env.COHERE_API_KEY}`, }, body: JSON.stringify({ model: 'command-xlarge-nightly', prompt: `User: ${prompt}\nBot:`, max_tokens: 100, }), }); const data = await response.json(); res.json(data.generations[0].text.trim()); } catch (error) { console.error('Error calling Cohere API:', error); res.status(500).json({ error: 'Failed to generate response' }); } }); app.listen(PORT, () => { console.log(`Server running on http://localhost:${PORT}`); });
  1. Create a .env file in the server directory:
COHERE_API_KEY=your_cohere_api_key_here
  1. Start the server:
node server.js

\ Important: Never share your .env file or commit it to version control. Add .env to your .gitignore file.

\

Step 3: Build the Chatbot Interface

Update the App.jsx file with the following code:

\

import React, { useState } from 'react'; import './App.css'; const App = () => { const [messages, setMessages] = useState([]); const [userInput, setUserInput] = useState(''); const [loading, setLoading] = useState(false); const sendMessage = async () => { if (!userInput.trim()) return; const newMessages = [...messages, { sender: 'user', text: userInput }]; setMessages(newMessages); setUserInput(''); setLoading(true); try { const response = await fetch('http://localhost:5000/generate', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ prompt: userInput }), }); const botReply = await response.text(); setMessages([...newMessages, { sender: 'bot', text: botReply }]); } catch (error) { console.error('Error fetching bot reply:', error); setMessages([ ...newMessages, { sender: 'bot', text: 'Sorry, something went wrong.' }, ]); } finally { setLoading(false); } }; return (
{messages.map((msg, index) => (
{msg.text}
))} {loading &&
Typing...
}
setUserInput(e.target.value)} placeholder="Type your message..." />
); }; export default App; Step 4: Add Styling

Create a file named App.css for styling the chatbot interface:

code.chat-container { font-family: Arial, sans-serif; max-width: 500px; margin: 20px auto; } .chatbox { border: 1px solid #ccc; padding: 10px; height: 400px; overflow-y: auto; border-radius: 5px; margin-bottom: 10px; } .message { margin: 5px 0; padding: 10px; border-radius: 5px; } .message.user { background-color: #d1e7dd; text-align: right; } .message.bot { background-color: #f8d7da; text-align: left; } .input-container { display: flex; } input { flex: 1; padding: 10px; border: 1px solid #ccc; border-radius: 5px 0 0 5px; } button { padding: 10px; border: 1px solid #ccc; border-radius: 0 5px 5px 0; background-color: #007bff; color: white; cursor: pointer; } Step 5: Test Your Chatbot
  1. Run the React app and the server simultaneously. You can use concurrently or open two terminals:

\

  • Terminal 1:
npm run dev
  • Terminal 2 (inside server):
node server.js

\

  1. Open the React app in your browser.
  2. Type a message and send it. The request will go to your Express server, which will securely call Cohere’s API and return the result.

\ Chatbot using AI Cohere's API

Repository

You can find the complete source code for this project on GitHub: AI Chatbot with React and Cohere. Feel free to clone it, explore the code, and customize it to your needs!

Conclusion

You’ve built a functional AI-powered chatbot using React, Vite, Cohere and Express. This project can be enhanced with features like:

\

  • Speech-to-text and text-to-speech integration.
  • Persistent conversations stored in a database.
  • A more polished design using a CSS framework like Tailwind.
  • Deploy the server using services like Heroku, AWS, or Vercel.

\ Start experimenting and happy coding!

\