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

Thursday, 22 June 2023

Building a Bio generator for twitter and linkedin using Worqhat AI model

Building BioGenApp: A Next.js Bio Generator with Worqhat AI models

A web application powered by Next.js that allows users to generate personalized Twitter or LinkedIn bio descriptions using AI-generated text.

- `app/index.tsx`: This file contains the main page component where the Bio Generator functionality is implemented.

- `app/Layout.tsx`: This file defines the layout component used to provide a consistent structure for the pages.

- `app/globals.css`: This file contains global styles for the application.

Getting Started

To get started with BioGenApp, make sure you have Node.js and npm installed on your machine. Then, follow these steps:

1. Create a new Next.js project called BioGenApp using the following command:

   ```bash

   npx create-next-app biogenapp

   ```

2. Navigate to the project directory:

   ```bash

   cd biogenapp

   ```

3. Replace the contents of the `pages/index.tsx` file with the following code:

   "use client"

    import { IconSquareRoundedNumber1Filled, IconSquareRoundedNumber2Filled, IconSquareRoundedNumber3Filled } from "@tabler/icons-react";

   import React, { useEffect, useState } from 'react';

   import React from 'react';

   import Layout from './Layout';

   import './globals.css';

   const Home = () => {

     // Bio Generator implementation

     return (

       <Layout>

         {/* Bio Generator UI */}

       </Layout>

     );

   };

   export default Home;

   ```

4. Replace the contents of the `app/Layout.tsx` file with the desired layout structure for your application.

5. Update the `styles/globals.css` file with custom styles to define the look and feel of your application.

Implementing the Bio Generator

Inside the `pages/index.tsx` file, you can implement the Bio Generator functionality. This includes capturing user input, making API calls, and rendering the generated bio descriptions.

To create a form for the user to input their bio details, you can use HTML input elements or React components such as `<input>` or `<textarea>`. Style them accordingly using CSS or CSS-in-JS libraries like styled-components.

```

import React, { useState } from 'react';

import Layout from './Layout';

import '../styles/globals.css';

const MyPage = () => {

  const [textAreaValue, setTextAreaValue] = useState('');

  const [vibeValue, setVibeValue] = useState('');

  const [platformValue, setPlatformValue] = useState('');

  const [generatedBio, setGeneratedBio] = useState('');

  const handleGenerateBioClick = async () => {

    let question = '';

    // Create the question based on the input values

    if (platformValue === 'Linkedin') {

      question = `Generate a ${vibeValue.toLowerCase()} LinkedIn bio: ${textAreaValue}`;

    } else if (platformValue === 'Twitter') {

      question = `Create a ${vibeValue.toLowerCase()} Twitter bio: ${textAreaValue}`;

    }

    const responseData = await fetchBioData(question, true, {}, 0.1);

    setGeneratedBio(responseData?.content || '');

  };

  return (

    <Layout>

      <div className="container">

        <div>

          <h1>Generate your next Twitter bio using Chatgpt</h1>

        </div>


        <div className="icon-heading">

          <IconSquareRoundedNumber1Filled size={32} />

          <h2 className="steps">Copy your current bio</h2>

        </div>

        <textarea

          className="my-textarea"

          placeholder="eg. Senior Developer Advocate @Worqhat. Tweeting about web development, AI, and React / Next.js, Writing nutlope.substack.com."

          value={textAreaValue}

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

        />

        <div className="icon-heading">

          <IconSquareRoundedNumber2Filled size={32} />

          <h2 className="steps">Select your vibe</h2>

        </div>

        <div>

          <select

            className="menuvibe"

            value={vibeValue}

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

          >

            <option value="">Select an option</option>

            <option value="Professional">Professional</option>

            <option value="Casual">Casual</option>

            <option value="Funny">Funny</option>

          </select>

        </div>

        <div className="icon-heading">

          <IconSquareRoundedNumber3Filled size={32} />

          <h2 className="steps">Select the platform</h2>

        </div>

        <div>

          <select

            className="menuplatform"

            value={platformValue}

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

          >

            <option value="">Select an option</option>

            <option value="Linkedin">Linkedin</option>

            <option value="Twitter">Twitter</option>

          </select>

        </div>

        <button className="generatebtn" onClick={handleGenerateBioClick}>

          Generate your bio

        </button>

        {generatedBio && (

  <div 

  className="generated-bio-container">

    <h2 className="generated-bio-heading">Your Generated Bio</h2>

    <p className="generated-bio">

      {generatedBio}

    </p>

  </div>

)}

      </div>

    </Layout>

  );

};

export default MyPage;

```

You can further enhance the functionality by implementing the API calls to generate the bio descriptions based on the user's input. Additionally, you can style the components using CSS classes or CSS-in-JS libraries like styled-components.

# Conclusion

We learned how to build BioGenApp, a Next.js web application for generating personalized Twitter or LinkedIn bio descriptions. We explored the project structure, implemented the Bio Generator UI, and discussed the next steps for integrating the bio generation functionality with Worqhat Ai models.

Feel free to ask and expand knowledge on this project based on your requirements. Happy coding!

Worqhat

View project on github

Monday, 12 June 2023

Building a Text to Code Generator with Next.js | Worqhat

 Do you often find yourself converting text-based requirements or ideas into code? Manually translating text into code can be time-consuming and error-prone. In this tutorial, we will build a Text to Code Generator using Next.js, a popular React framework, to automate the process of generating code from text input.

Prerequisites
Before get started, make sure you have the following:

Node.js and npm installed on your machine.
Basic knowledge of JavaScript and React.
Familiarity with Next.js and its project structure.

Setting Up the Project

To start, let's create a new Next.js project and set up the necessary dependencies. Open your terminal and follow these steps:
  • Create a new Next.js project:
        npx create-next-app text-to-code-generator
  • Change into the project directory:
        cd text-to-code-generator
  • Install additional dependencies:
       npm install @monaco-editor/react 
          npm install next react react-dom @monaco-editor/react    
  • Open the package.json file and update the scripts section as follows:
        "scripts": { "dev": "next dev" },
Integrating Monaco Editor

The Monaco Editor is a powerful web-based code editor that we will use for our Text to Code Generator. Let's create a new component called CodeEditor that integrates with Monaco Editor. Open the file components/editor.jsx and add the following code:

import { useEffect } from 'react'; 
import { Editor } from '@monaco-editor/react';
 export default function CodeEditor({ editorRef }) {
 useEffect(() => { 
if (editorRef.current) { 
editorRef.current.focus(); } }, 
[]);
 return (
 <Editor 
height="40vh" 
fontSize="14px" 
theme="vs-dark" 
defaultLanguage="javascript" 
ref={editorRef} 
margin="auto"
 /> ); }

Here, we import the necessary dependencies and create a functional component CodeEditor. The useEffect hook ensures that the editor receives focus when it is rendered. The Editor component renders the Monaco Editor with customizable properties such as height, font size, theme, and default language.

Creating the User Interface

Now, let's build the user interface for our Text to Code Generator. Open the file pages/index.js and replace the existing code with the following:

import { useRef } from 'react';
import CodeEditor from '../components/editor';

export default function Home() {
  const editorRef = useRef(null);

  const handleGenerateCodeClick = () => {
    const textBoxValue = document.getElementById('textbox1').value;
    const selectedLanguage = document.getElementById('language').value;

    // Perform actions with textBoxValue and selectedLanguage
    alert('Entered Text: ' + textBoxValue);
    alert('Selected Language: ' + selectedLanguage);
  };

  return (
    <div className="container">
      <h1>Text to Code Generator</h1>
      <input type="text" id="textbox1" className="input-animation" placeholder="Enter your text" />
      <div>
        <select id="language" className="select-animation">
          <option value="">Select language</option>
          <option value="cpp">C++</option>
          <option value="python">Python</option>
          <option value="java">Java</option>
          <option value="javascript">JavaScript</option>
          <option value="php">PHP</option>
        </select>
      </div>
      <button id="generateButton" onClick={handleGenerateCodeClick}>Generate Code</button>
      <div className="edit">
        <CodeEditor editorRef={editorRef} />
        <br></br>
      </div>
    </div>
  );
}


In this code, we import the useRef hook and the CodeEditor component. We create a handleGenerateCodeClick function that retrieves the values from the text input and language selection elements and performs actions based on the user's input. The UI consists of a text input, a language selection dropdown, a "Generate Code" button, and the CodeEditor component.

Styling the User Interface:

To add some visual appeal to our Text to Code Generator, we can apply CSS styles. Create a new file called globals.css in the styles directory and add the following styles:

/* styles/globals.css */

.container {
  max-width: 600px;
  margin: 0 auto;
  padding: 40px;
  text-align: center;
}

.input-animation {
  /* Add your animation styles here */
}

.select-animation {
  /* Add your animation styles here */
}

.edit {
  margin-top: 40px;
}


These styles define the appearance of the container, input elements, and the CodeEditor component. You can customize the styles to match your preferences. Running the Application
To run the Text to Code Generator, execute the following command in your terminal:

        npm run dev

Open your browser and navigate to http://localhost:3000. You should see the Text to Code Generator with the input elements and the code editor. Enter some text, select a language, and click the "Generate Code" button to see the alerts displaying the entered text and selected language.

Conclusion

now we have successfully built a Text to Code Generator using Next.js and Monaco Editor. This project automates the process of generating code from text input, making it more efficient and reducing the chances of manual errors. You can further enhance this project by integrating code generation logic based on the selected language or by adding additional features to the user interface.

Feel free to explore the complete source code of this project on GitHub. If you have any questions or feedback, please leave a comment below.

Happy coding!