Thursday, 29 June 2023

Building Ai chatbot web application using Next js and Worqhat AI models

Worqhat Chatbot Documentation


This documentation provides an in-depth guide on how to set up, run, customize, and implement the Worqhat Chatbot project. 

The Worqhat Chatbot is a web application developed using Next.js that interacts with the Worqhat AI content API to generate responses based on user input.


Prerequisites

Before you begin, ensure that you have the following prerequisites installed on your machine:

Node.js: The runtime environment for running JavaScript applications.

npm (Node Package Manager) or Yarn: Package managers for installing and managing project dependencies.

Getting Started

Follow the step-by-step instructions below to set up and run the Worqhat Chatbot project on your local machine:

Clone the Repository

Start by cloning the Worqhat Chatbot repository from the GitHub repository. Open your terminal and run the following command:

bash

gh repo clone prajwald2607/Ai-chatbot-nextjs

Alternatively, you can download the source code as a ZIP file from the repository and extract it to a local directory.

Install Dependencies

Open a terminal window and navigate to the project directory:

cd my-chatbot

Use the package manager of your choice (npm or Yarn) to install the project dependencies. Run the following command:

npm install

or

yarn install

Configure API Keys

Obtain the necessary API keys from the Worqhat platform. These keys are required to authenticate and access the Worqhat AI content API.

Open the pages.tsx file located in the project directory using a text editor.

Replace the placeholder values for the x-api-key and x-org-key headers in the handleSendMessage function with your actual API keys.

Start the Development Server

In the terminal, run the following command to start the development server:

npm run dev

or

yarn dev

The Worqhat Chatbot should now be up and running on http://localhost:3000.

Implementation


To implement the Worqhat Chatbot in your web application, follow these steps:

Import the required modules at the beginning of your file:


import Image from 'next/image';

import React, { useState } from 'react';

import ReactDOMServer from 'react-dom/server';

Define the HomePage component, which will contain the chatbot functionality:


const HomePage = () => {

  // State variables

  const [message, setMessage] = useState('');

  const [apiResponse, setApiResponse] = useState('');

  const [isLoading, setIsLoading] = useState(false);

  const [messageHistory, setMessageHistory] = useState([]);


  // Function to handle sending a message and receiving a response

  const handleSendMessage = async () => {

    setIsLoading(true);

    try {

      // Prepare the request body

      const requestBody = {

        question: message,

        randomness: 0.1 // Adjust the randomness factor as needed

      };

      // Send the request to the API

      const response = await fetch('https://api.worqhat.com/api/ai/content/v2', {

        method: 'POST',

        headers: {

          'Content-Type': 'application/json',

          'x-api-key': 'api-key',

          'x-org-key': 'org-key'

        },

        body: JSON.stringify(requestBody)

      });

      // Parse the API response

      const data = await response.json();

      // Update the state with the API generated response

      setApiResponse(data.content);

      // Add the current message to the message history

      setMessageHistory(prevHistory => [

        ...prevHistory,

        { message, response: data.content }

      ]);

    } catch (error) {

      console.error('Error:', error);

    } finally {

      setIsLoading(false);

    }

  };

  // Render the component JSX

  return (

    <div>

      <div className='container'>

        <h1>Worqhat Chatbot</h1>

        <div className='history'>

          <div className='message-history'>

            {messageHistory.map((item, index) => (

              <div key={index} className='message-item'>

                <div className='message'>{item.message}</div>

                <div className='response'>{item.response}</div>

              </div>

            ))}

          </div>

        </div>

        <div className='tp'>

          <input

            className='inputt'

            type="text"

            placeholder='Send a message'

            value={message}

            onChange={(e) => setMessage(e.target.value)}

          />

          <button className='send' onClick={handleSendMessage} disabled={isLoading}>

            {isLoading ? 'Loading...' : 'Send'}

          </button>

        </div>

      </div>

      <div className='logo' style={{ display: 'flex', justifyContent: 'center', alignItems: 'center' }}>

        <h2>Powered By</h2>

        <Image src="/logo.png" alt="Logo" width={100} height={50} />

      </div>

    </div>

  );

};

export default HomePage;

Customize the component as needed, such as adding styling or additional functionality.

Use the HomePage component in your application where you want to integrate the Worqhat Chatbot.

Deployment

To deploy the Worqhat Chatbot project to a production environment, follow these general steps:

Build the production-ready application:

npm run build

or

yarn build

Deploy the built application using your preferred hosting service or platform. Next.js supports various deployment options, including but not limited to Vercel, AWS Amplify, and Netlify. Refer to the official Next.js documentation for detailed deployment instructions based on your chosen platform.

Configure any environment variables or settings required for your production deployment, such as API keys or server-specific configurations.

Monitor the deployed application and ensure that it is functioning correctly in the production environment. Make any necessary adjustments or bug fixes as needed.

Troubleshooting

If you encounter any issues during the setup or usage of the Worqhat Chatbot project, consider the following troubleshooting steps:

Check Dependencies: Ensure that you have installed all the required dependencies specified in the package.json file. Run npm install or yarn install again to ensure everything is up to date.

Verify API Keys: Double-check that the API keys used for authentication are correct and have the necessary permissions to access the Worqhat AI content API.

Review Error Messages: Examine any error messages displayed in the browser console or terminal for potential clues about the cause of the issue. If you need further assistance, search for the specific error message or consult the Worqhat Chatbot community for support.

Update Dependencies: Regularly update the project dependencies to the latest versions to benefit from bug fixes and new features. Use npm update or yarn upgrade to update the packages while considering compatibility with other dependencies.

Conclusion

Congratulations! You have successfully set up and implemented the Worqhat Chatbot project. You can now integrate the chatbot functionality into your web application and provide an interactive conversational experience for your users. Remember to refer to the documentation and community resources for further customization options and troubleshooting assistance.

With 💖 from Worqhat 

Github repo

No comments:

Post a Comment