Create a chatbot interface using React, Tailwind CSS and Redux. The interface must…
- User
Create a chatbot interface using React, Tailwind CSS and Redux. The interface must support the following features:
- connection to the chatbot API with Javascript
- a text input for interacting with the chatbot
- the ability to retain past chats
- support for proper formatting
- support for copying
This is the API information provided by the website in Javascript: import { Client } from "@gradio/client";
const client = await Client.connect("yuntian-deng/o1mini"); const result = await client.predict("/predict", { inputs: "Hello!!", top_p: 0, temperature: 0, chat_counter: 3, chatbot: [["Hello!",None]], });
console.log(result.data);
- Assistant
Creating a chatbot interface with React, Tailwind CSS, and Redux involves several steps, including setting up the project, configuring Redux for state management, connecting to the chatbot API, and designing the user interface with the required features. Below is a comprehensive guide to help you build this chatbot interface.
Table of Contents
- Project Setup
- Installing Dependencies
- Project Structure
- Configuring Redux
- Creating the Chatbot API Service
- Building React Components
- Styling with Tailwind CSS
- Final Touches
- Running the Application
Project Setup
First, ensure that you have Node.js and npm installed on your machine. Then, create a new React project using Create React App.
npx create-react-app chatbot-interface cd chatbot-interfaceInstalling Dependencies
Install the necessary dependencies including Redux, React-Redux, Redux Toolkit, Tailwind CSS, and the Gradio client.
npm install @reduxjs/toolkit react-redux @gradio/clientSet up Tailwind CSS by following the official Tailwind CSS installation guide. For convenience, here's a summary:
-
Install Tailwind CSS and its dependencies:
npm install -D tailwindcss postcss autoprefixer npx tailwindcss init -p -
Configure
tailwind.config.js:// tailwind.config.js module.exports = { content: [ "./src/**/*.{js,jsx,ts,tsx}", ], theme: { extend: {}, }, plugins: [], } -
Add Tailwind directives to
src/index.css:/* src/index.css */ @tailwind base; @tailwind components; @tailwind utilities;
Project Structure
Organize your project files for better maintainability. Here's a suggested structure:
chatbot-interface/ ├── src/ │ ├── components/ │ │ ├── ChatBox.jsx │ │ ├── Message.jsx │ │ └── InputBox.jsx │ ├── redux/ │ │ ├── store.js │ │ └── chatSlice.js │ ├── services/ │ │ └── chatbotApi.js │ ├── App.js │ ├── index.js │ └── index.css ├── tailwind.config.js └── package.jsonConfiguring Redux
1. Create the Redux Store
Create a
store.jsfile inside thereduxdirectory.// src/redux/store.js import { configureStore } from '@reduxjs/toolkit'; import chatReducer from './chatSlice'; const store = configureStore({ reducer: { chat: chatReducer, }, }); export default store;2. Create the Chat Slice
Create a
chatSlice.jsfile inside thereduxdirectory to manage chat state.// src/redux/chatSlice.js import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'; import { getChatbotResponse } from '../services/chatbotApi'; export const fetchChatbotResponse = createAsyncThunk( 'chat/fetchResponse', async (userInput, { getState }) => { const { chat } = getState(); const response = await getChatbotResponse(userInput, chat.messages); return response; } ); const chatSlice = createSlice({ name: 'chat', initialState: { messages: [], // { sender: 'user' | 'bot', text: 'message text' } loading: false, error: null, }, reducers: { addMessage: (state, action) => { state.messages.push(action.payload); }, clearChat: (state) => { state.messages = []; }, }, extraReducers: (builder) => { builder .addCase(fetchChatbotResponse.pending, (state) => { state.loading = true; state.error = null; }) .addCase(fetchChatbotResponse.fulfilled, (state, action) => { state.loading = false; state.messages.push({ sender: 'bot', text: action.payload }); }) .addCase(fetchChatbotResponse.rejected, (state, action) => { state.loading = false; state.error = action.error.message; }); }, }); export const { addMessage, clearChat } = chatSlice.actions; export default chatSlice.reducer;Creating the Chatbot API Service
Create a
chatbotApi.jsfile inside theservicesdirectory to handle API interactions.// src/services/chatbotApi.js import { Client } from "@gradio/client"; let client; const initializeClient = async () => { if (!client) { client = await Client.connect("yuntian-deng/o1mini"); } }; export const getChatbotResponse = async (userInput, previousMessages) => { await initializeClient(); // Format the previous messages as required by the API const chatbotHistory = previousMessages .filter(msg => msg.sender === 'bot' || msg.sender === 'user') .map(msg => [msg.sender === 'user' ? msg.text : msg.text, null]); const response = await client.predict("/predict", { inputs: userInput, top_p: 0, temperature: 0, chat_counter: previousMessages.length, chatbot: chatbotHistory, }); return response.data; };Building React Components
1. App Component
Modify
App.jsto include theChatBoxcomponent and provide the Redux store.// src/App.js import React from 'react'; import ChatBox from './components/ChatBox'; function App() { return ( <div className="min-h-screen bg-gray-100 flex items-center justify-center p-4"> <ChatBox /> </div> ); } export default App;2. ChatBox Component
Create a
ChatBox.jsxfile inside thecomponentsdirectory to display chat messages and the input box.// src/components/ChatBox.jsx import React from 'react'; import { useSelector, useDispatch } from 'react-redux'; import Message from './Message'; import InputBox from './InputBox'; import { clearChat } from '../redux/chatSlice'; const ChatBox = () => { const messages = useSelector((state) => state.chat.messages); const loading = useSelector((state) => state.chat.loading); const error = useSelector((state) => state.chat.error); const dispatch = useDispatch(); const handleClear = () => { dispatch(clearChat()); }; return ( <div className="w-full max-w-2xl bg-white rounded-lg shadow-lg flex flex-col h-[80vh]"> <div className="flex justify-between items-center p-4 border-b"> <h2 className="text-xl font-semibold">Chatbot</h2> <button onClick={handleClear} className="text-red-500 hover:text-red-700" > Clear </button> </div> <div className="flex-1 overflow-y-auto p-4"> {messages.length === 0 && ( <p className="text-gray-500">Start the conversation!</p> )} {messages.map((msg, index) => ( <Message key={index} sender={msg.sender} text={msg.text} /> ))} {loading && ( <div className="text-gray-500">Bot is typing...</div> )} {error && ( <div className="text-red-500">Error: {error}</div> )} </div> <InputBox /> </div> ); }; export default ChatBox;3. Message Component
Create a
Message.jsxfile inside thecomponentsdirectory to display individual messages.// src/components/Message.jsx import React from 'react'; const Message = ({ sender, text }) => { const isUser = sender === 'user'; return ( <div className={`flex ${isUser ? 'justify-end' : 'justify-start'} mb-2`}> <div className={`max-w-xs md:max-w-md lg:max-w-lg p-3 rounded-lg ${isUser ? 'bg-blue-500 text-white' : 'bg-gray-200 text-gray-800'} break-words`} > <pre className="whitespace-pre-wrap">{text}</pre> <button onClick={() => navigator.clipboard.writeText(text)} className="text-xs text-gray-600 mt-1 hover:underline" > Copy </button> </div> </div> ); }; export default Message;4. InputBox Component
Create an
InputBox.jsxfile inside thecomponentsdirectory for user input.// src/components/InputBox.jsx import React, { useState } from 'react'; import { useDispatch } from 'react-redux'; import { addMessage, fetchChatbotResponse } from '../redux/chatSlice'; const InputBox = () => { const [input, setInput] = useState(''); const dispatch = useDispatch(); const handleSend = () => { const trimmedInput = input.trim(); if (trimmedInput === '') return; // Add user message dispatch(addMessage({ sender: 'user', text: trimmedInput })); // Fetch bot response dispatch(fetchChatbotResponse(trimmedInput)); setInput(''); }; const handleKeyPress = (e) => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); handleSend(); } }; return ( <div className="p-4 border-t"> <textarea className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring focus:border-blue-300 resize-none" rows={2} placeholder="Type your message..." value={input} onChange={(e) => setInput(e.target.value)} onKeyPress={handleKeyPress} ></textarea> <button onClick={handleSend} className="mt-2 px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600" > Send </button> </div> ); }; export default InputBox;Styling with Tailwind CSS
Tailwind CSS has been integrated into the project as per the installation steps. The provided components utilize Tailwind classes for styling. Here's a brief overview of how Tailwind is used:
-
Container Styling: The
ChatBoxcomponent uses classes likebg-white,rounded-lg, andshadow-lgto style the chat container. -
Message Styling: The
Messagecomponent differentiates between user and bot messages using conditional classes (bg-blue-500for user andbg-gray-200for bot). -
Input Styling: The
InputBoxcomponent styles the textarea and send button for a clean input area.
Feel free to customize the Tailwind classes to match your desired design aesthetics.
Final Touches
1. Connecting Redux Store
Ensure that the Redux store is connected to your React application. Modify
index.jsas follows:// src/index.js import React from 'react'; import ReactDOM from 'react-dom/client'; import './index.css'; import App from './App'; import store from './redux/store'; import { Provider } from 'react-redux'; const root = ReactDOM.createRoot(document.getElementById('root')); root.render( <Provider store={store}> <App /> </Provider> );2. Handling API Initialization Errors
It's good practice to handle potential errors during the API client initialization. Update the
chatbotApi.jsto include error handling.// src/services/chatbotApi.js import { Client } from "@gradio/client"; let client; const initializeClient = async () => { if (!client) { try { client = await Client.connect("yuntian-deng/o1mini"); } catch (error) { console.error("Failed to connect to the chatbot API:", error); throw error; } } }; export const getChatbotResponse = async (userInput, previousMessages) => { await initializeClient(); // Format the previous messages as required by the API const chatbotHistory = previousMessages .filter(msg => msg.sender === 'bot' || msg.sender === 'user') .map(msg => [msg.sender === 'user' ? msg.text : msg.text, null]); try { const response = await client.predict("/predict", { inputs: userInput, top_p: 0, temperature: 0, chat_counter: previousMessages.length, chatbot: chatbotHistory, }); return response.data; } catch (error) { console.error("Error fetching chatbot response:", error); throw error; } };Running the Application
After setting up all the components and configurations, you can run your application.
npm startOpen http://localhost:3000 to view the chatbot interface in your browser.
Features Breakdown
-
Connection to the Chatbot API: Utilizes the Gradio client to connect and communicate with the chatbot API asynchronously.
-
Text Input for Interaction: The
InputBoxcomponent provides a textarea for users to input their messages, which can be sent by clicking the "Send" button or pressingEnter. -
Retain Past Chats: The Redux store maintains an array of messages (
state.chat.messages) that persist throughout the chat session. Users can clear the chat history using the "Clear" button. -
Proper Formatting: Messages are displayed using the
pretag withwhitespace-pre-wrapto preserve formatting such as line breaks and indentation. -
Copying Support: Each message includes a "Copy" button that allows users to copy the message text to their clipboard easily.
Additional Enhancements
To further enhance the chatbot interface, consider implementing the following features:
-
Markdown Support: Integrate a markdown parser like react-markdown to render rich text formatting from the chatbot responses.
-
Loading Indicators: Improve user experience by adding more descriptive loading indicators or animations when the bot is generating a response.
-
Error Handling UI: Provide user-friendly error messages and potentially retry mechanisms if the chatbot API fails.
-
User Authentication: If needed, implement user authentication to manage individual chat sessions.
-
Responsive Design: Ensure that the chatbot interface is responsive and functions well on various screen sizes.
This guide provides a solid foundation for creating a functional and aesthetically pleasing chatbot interface using React, Tailwind CSS, and Redux. Feel free to customize and extend the functionalities to better suit your specific requirements.