Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ye bot revamp1 #710

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -74,12 +74,11 @@ Let’s learn what are the limitations of Playground, that makes it not generate
- **Not so many features**: Compared to the API, the Playground is a little limited. You can only type in prompts and get responses, whereas the API has a bunch of extra features like fine-tuning and training the models for specific tasks. So if you want to take your skills to the next level, you gotta upgrade, ya feel me?
- **Limited control**: When it comes to tweaking the model settings, you're kinda stuck with the basics like temperature, max tokens, and frequency penalty. If you're looking for more customization, you gotta use the API or some other tool.
- **Usage limits**: Oh, and one more thing – there's a limit on how much you can use the Playground in an hour. So if you're using it a lot, keep that in mind, my dude.
- **Cannot train model:** Playground interface doesn’t allow us to train the models to our specific needs.

## Why we need to train our models using prompts
## Why You Should Use the OpenAI API with Prompts

As the Playground is not effective, this is where code and prompts come in!
While the OpenAI Playground is great for quick experimentation, it’s not built to support fully functioning applications like a chatbot.

Prompts are the key to training a dope model. With code and prompts, you can give GPT specific cues on how to respond to certain inputs. This means you can get way more effective and predictable responses from your model.
To build a chatbot that consistently imitates Kanye West, you need the OpenAI API. The API allows you to integrate the model into an application, handle dynamic interactions, and maintain conversation context.

In the next chapter, we will use code and prompts to train our model. We will train our model such that it will act like Kanye and give us the dope answers.
In the next section, we’ll explore how to use the OpenAI API to build a YeBot.
Original file line number Diff line number Diff line change
Expand Up @@ -7,46 +7,124 @@ Now, let’s dive into the dope world of the YeAI Bot Project. This project is a
Check out some of the key features of the YeAI Bot Project:

- Understanding natural language input so you can talk to it like a real person.
- Improving accuracy of responses through machine learning-based training using prompts.
- Use of the amazing openAI GPT-4 model to generate responses that sound real.
- Personalizing responses based on your interactions and data, so it feels like you're chatting with a real Kanye West.
- Integrate the model with NextJS and run the server using Flask.

## Let's Get It Started: Code & Prompts

We’ll be using code and prompts to build our YeBot. As we have learned in previous lessons that how effective the prompts are, we will use them to train our model and build the dope shit!

To train our model, we'll use MindsDB Cloud and the OpenAI engine. By setting up our development environment and using an OpenAI API key we have already generated.
We’ll be using code and prompts to build our YeBot, with the OpenAI engine as the backbone of our chatbot. We’ll set up our development environment and use the OpenAI API key that we’ve already generated for this purpose. To build the frontend, we’ll be using NextJS which will allow us to create an interactive and dynamic user interface for our Kanye West AI chatbot.

**Don’t Worry**! We will explain everything one-by-one. So, let’s buckle up to learn and build!

## Setup your development environment
## So, why use Next.js for building a YeAI bot?

Next.js is a super cool framework for building web apps, and it's perfect for building dope projects like a Kanye West AI bot using OpenAI API. Let me break it down for you real quick:

- It's perfect for building complex apps that require dynamic data and frequent updates, like our YeAI bot that's constantly learning and evolving.
- It's super fast and efficient, which is important when you're dealing with large amounts of data and processing power, which our GPT model will be using to give us responses.
- It's easy to use and has a ton of awesome features that will make building your AI bot a breeze.
- It's super fun and exciting to work with, especially when you're building something as cool as a Kanye West AI bot!

> **Note:** If you have not installed NodeJs in your system, head over to [https://nodejs.org/en/download](https://nodejs.org/en/download) and install it.
>

Let’s get started and build dope stuff!


- **`npm init -y`**: Quickly initializes a new Node.js project by creating a `package.json` file with default settings.
- **`npm install axios`**: Installs the `axios` library for making HTTP requests and adds it as a dependency in `package.json`.

## Getting started with Node.js
Run this command in your terminal to initializes a new Node.js project by creating a `package.json` file with default settings.

`npm init -y`

Now run this command to install the `axios` library for making HTTP requests and adds it as a dependency in `package.json`.

`npm install axios`

We need 'axios' to make HTTPS requests to communicate with external services like APIs over the internet. It ensures that the data being exchanged is encrypted which protects it from interception or tampering. For our YeBot, HTTPS requests are used to send user input to OpenAI's API and receive a response securely.

## Code

Now create a new file `chatbot.js` and paste this code:

```
const axios = require('axios');
const dotenv = require('dotenv');

dotenv.config();

async function getKanyeResponse(userMessage) {
const apiKey = process.env.OPENAI_API_KEY;

try {
const response = await axios.post('https://api.openai.com/v1/chat/completions', {
model: 'gpt-3.5-turbo',
messages: [
{
role: 'system',
content: 'Respond as if you are Kanye West, the iconic rapper and producer known for his bold, passionate, and often controversial statements, characterized by a confident, stream-of-consciousness style, inventive language, and a mix of emotional intensity and unpredictable tweets.'
},
{
role: 'user',
content: userMessage,
},
],
}, {
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json',
},
});

const botResponse = response.data.choices[0]?.message?.content || 'No response from bot';
console.log("Kanye Bot:", botResponse);
} catch (error) {
console.error('Error:', error);
}
}

// Call the function with a user message
getKanyeResponse('What do you think about your latest album?');
```

### Explanation

Here's a breakdown of the key elements in the Node.js file:

1. `dotenv.config()`: This loads environment variables from a .env file into process.env, making it easier to store sensitive data like the OpenAI API key.

2. `async function getKanyeResponse(userMessage)`: Defines an asynchronous function that takes in the `userMessage` (the message sent by the user) and sends it to the OpenAI API to generate a Kanye-like response.

3. `process.env.OPENAI_API_KEY`: Retrieves the OpenAI API key stored in the .env file. This API key is used to authenticate requests to OpenAI.

4. `axios.post()`: This sends a POST request to the OpenAI API's `/chat/completions` endpoint. It provides a chat-based conversation with:

- model: The GPT model to be used (`gpt-3.5-turbo`).
- messages: A conversation format where the system sets up Kanye's tone, and the user's message is passed.

First things first! Let’s setup our development environment and learn what the hell is MindsDB.
5. Response handling: It extracts the response text from OpenAI's API, logs it to the console, and defaults to "No response from bot" if no message is received.

## What is MindsDB?
6. Error handling: Catches and logs any errors that occur during the API request process.

Now, if you ain't heard of MindsDB, let me put you on. It's an open-source tool that makes it easy for anyone to create and train machine learning models. You can use it to build all sorts of AI bots, from chatbots to recommendation systems.
## Create a .env file

## Why MindsDB for YeAI development, you ask?
Create a new file by the name `.env` and paste this:

- MindsDB is perfect for Kanye AI bot development 'cause' we can code in MindsDB and it's super easy to use, even if you're not a data scientist or a machine learning whiz.
- We can use as many models as we can in MindsDB. You want to use GPT-3? You want to use GPT-4? You got all of this!
- In MindsDB, we have full control, we can use as many features as we can.
- There’s no limit in MindsDB, you can use it for as long as you want to use it.
- Above all, we can easily train our model using prompts!
`OPENAI_API_KEY=<you-API-key>`

## Setting up the Development Environment on MindsDB Cloud
Be sure to replace the placeholder (`<you-API-key>`) with the API key you generateed in the previous chapter.

Here's how to set up the development environment on MindsDB Cloud:
### But why do we need a .env file?

- **Step 1:** Sign up for an account on [MindsDB Cloud](https://cloud.mindsdb.com/login?utm_medium=referral&utm_source=medium&utm_campaign=twitter-chatbot-tutorial-2023-03).
- **Step 2:** Go to [https://cloud.mindsdb.com/editor](https://cloud.mindsdb.com/editor).
By storing the API key in a `.env` file and preventing it from being hard-coded in the main code, we are reducing the risk of accidentally exposing it in public repositories or version control systems like Git. It's good practice to store any sensitive information in a .env file and access it from there.

MindsDB editor looks like this:
## Let's run the code

![Untitled](https://github.com/0xmetaschool/Learning-Projects/raw/main/Build%20a%20YeBot%20with%20OpenAI%20API/3.%20Let%E2%80%99s%20Build%20Some%20Dope%20Shit/Building%20the%20YeBot!%203dd9862e53234b329875e7c69ae64c11/Untitled.png)
Run this command in your terminal:

Now that we have setup the MindsDB, we will learn how to run our model in MindsDB in the next lesson.
`node chatbot.js`

Get ready for some serious fun with this project, y'all!
Boom! There it is. Just like that. Magic, no cap.
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# Connect this Yeezy to a NextJS app
<!-- # Connect this Yeezy to a NextJS app

Yo, listen up! We 'bout to make some moves and get connected to NextJS App using Python Flask.

Expand All @@ -24,11 +24,13 @@ Here are a few reasons:
> **Note:** If you have not installed NodeJs in your system, head over to [https://nodejs.org/en/download](https://nodejs.org/en/download) and install it.
>

Let’s get started and build dope stuff!
Let’s get started and build dope stuff! -->

Yo, listen up! We 'bout to make some moves and get connected to NextJS App using Python Flask.

## Create a NextJS app for the frontend

First, we will now create a NextJS frontend, run this command in your terminal to create your NextJS app.
First, we will create a NextJS frontend, run this command in your terminal to create your NextJS app.

```jsx
npx create-next-app kanye-ai
Expand Down Expand Up @@ -71,114 +73,105 @@ import React, { useState } from "react";
import Head from "next/head";
import axios from "axios";

function iMessage() {
function ChatBot() {
const [userInput, setUserInput] = useState("");
const [messages, setMessages] = useState([]);
const [kanyeTyping, setKanyeTyping] = useState(false);

const handleChange = (event) => {
setUserInput(event.target.value);
};
console.log(messages)

const handleSubmit = async (event) => {
event.preventDefault();
const newMessage = { user: true, text: userInput };
setMessages([...messages, newMessage, { user: false, text: "loading" }]);
setKanyeTyping(true);
axios.post('http://localhost:8080/bot', {

try {
const response = await axios.post('/api/chat', {
message: userInput
}, {
headers: {
'Content-Type': 'application/json',
},
withCredentials: true
}).then((response) => {
console.log(response);
// Update messages and setKanyeTyping to false when you receive the response
const botResponse = { user: false, text: response.data.results[0].response };
setMessages([...messages, newMessage, botResponse]);
setKanyeTyping(false);
}).catch((error) => {
console.error(error);
// Update messages and setKanyeTyping to false when you receive an error
const botResponse = { user: false, text: "Oops! Something went wrong." };
setMessages([...messages, newMessage, botResponse]);
setKanyeTyping(false);
});
setUserInput("");
setKanyeTyping(true);
});

const botResponse = { user: false, text: response.data.response || "No response from bot" };
setMessages([...messages, newMessage, botResponse]);
} catch (error) {
console.error(error);
const botResponse = { user: false, text: "Oops! Something went wrong." };
setMessages([...messages, newMessage, botResponse]);
} finally {
setKanyeTyping(false);
setUserInput("");
}
};


return (
<>
<Head>
<title>
Kanye West Chatbot - Metaschool
</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" />
</Head>
<div className="chat-container">
<div className="header">
<i className="fa fa-chevron-left back-button"></i>
<div className="contact-info">
<img
className="profile-image"
src="https://imageio.forbes.com/specials-images/imageserve/5ed00f17d4a99d0006d2e738/0x0.jpg?format=jpg&crop=4666,4663,x154,y651,safe&height=416&width=416&fit=bounds"
alt="Profile"
/>
<h2 className="name">YeGPT</h2>
</div>
<i className="fa fa-video-camera video-icon"></i>
</div>
<div className="chat-window">
<p className="chat-bot-header">Powered by <a className="ref-link" href="http://metaschool.so/" target="_blank" rel="noopener noreferrer">metaschool 🔮</a></p>
{messages.map((message, index) => (
<div key={index} className="message-container">
{message.user ? (
<>
<div className="user-message message">
<div className="message-text">{message.text}</div>
</div>
<img
className="profile-image user-image"
src={'https://upload.wikimedia.org/wikipedia/commons/thumb/5/59/User-avatar.svg/2048px-User-avatar.svg.png'}
alt="User Profile"
/>
</>
) : (
<>
<img
className="profile-image bot-image"
src='https://imageio.forbes.com/specials-images/imageserve/5ed00f17d4a99d0006d2e738/0x0.jpg?format=jpg&crop=4666,4663,x154,y651,safe&height=416&width=416&fit=bounds'
alt="Bot Profile"
/>
{message.text === 'loading' ? <img className="typing-bubble" src='https://media3.giphy.com/media/v1.Y2lkPTc5MGI3NjExODg3ZjFlNzQ1Mzc1ZTFlNTMyZTVjODIzMDYyODUwNDQ0ZDY3ZmU5YyZjdD1z/3tLfKrc4pLWiTkAAph/giphy.gif' /> : <div className="bot-message message">
<div className="message-text">{message.text}</div>
</div>}
</>
)}
</div>
))}
<Head>
<title>Kanye West Chatbot</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" />
</Head>
<div className="chat-container">
<div className="header">
<i className="fa fa-chevron-left back-button"></i>
<div className="contact-info">
<img
className="profile-image"
src="https://imageio.forbes.com/specials-images/imageserve/5ed00f17d4a99d0006d2e738/0x0.jpg?format=jpg&crop=4666,4663,x154,y651,safe&height=416&width=416&fit=bounds"
alt="Profile"
/>
<h2 className="name">YeGPT</h2>
</div>
<i className="fa fa-video-camera video-icon"></i>
</div>
<div className="chat-window">
<p className="chat-bot-header">Powered by <a className="ref-link" href="http://metaschool.so/" target="_blank" rel="noopener noreferrer">metaschool 🔮</a></p>
{messages.map((message, index) => (
<div key={index} className="message-container">
{message.user ? (
<>
<div className="user-message message">
<div className="message-text">{message.text}</div>
</div>
<img
className="profile-image user-image"
src={'https://upload.wikimedia.org/wikipedia/commons/thumb/5/59/User-avatar.svg/2048px-User-avatar.svg.png'}
alt="User Profile"
/>
</>
) : (
<>
<img
className="profile-image bot-image"
src='https://imageio.forbes.com/specials-images/imageserve/5ed00f17d4a99d0006d2e738/0x0.jpg?format=jpg&crop=4666,4663,x154,y651,safe&height=416&width=416&fit=bounds'
alt="Bot Profile"
/>
{message.text === 'loading' ? <img className="typing-bubble" src='https://media3.giphy.com/media/v1.Y2lkPTc5MGI3NjExODg3ZjFlNzQ1Mzc1ZTFlNTMyZTVjODIzMDYyODUwNDQ0ZDY3ZmU5YyZjdD1z/3tLfKrc4pLWiTkAAph/giphy.gif' /> : <div className="bot-message message">
<div className="message-text">{message.text}</div>
</div>}
</>
)}
</div>
<form className="form" onSubmit={handleSubmit}>
<input
type="text"
placeholder="Type your message here..."
value={userInput}
onChange={handleChange}
disabled={kanyeTyping}
/>
<button type="submit">
<i className="fa fa-paper-plane" aria-hidden="true"></i>
</button>
</form>
))}
</div>
<form className="form" onSubmit={handleSubmit}>
<input
type="text"
placeholder="Type your message here..."
value={userInput}
onChange={handleChange}
disabled={kanyeTyping}
/>
<button type="submit">
<i className="fa fa-paper-plane" aria-hidden="true"></i>
</button>
</form>
</div>
</>
);
}

export default iMessage;
export default ChatBot;
```

### Explanation
Expand Down