From f416b92451340b57794c26abf25ae082465695ad Mon Sep 17 00:00:00 2001 From: Aamna Kamran Date: Wed, 25 Sep 2024 17:34:05 +0500 Subject: [PATCH 1/3] removed references to training a model in the lesson --- ...2\200\231s Play with OpenAI Playground Like a Pro.md" | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git "a/Build a YeBot with OpenAI API/2. WTH is OpenAI/3. Let\342\200\231s Play with OpenAI Playground Like a Pro.md" "b/Build a YeBot with OpenAI API/2. WTH is OpenAI/3. Let\342\200\231s Play with OpenAI Playground Like a Pro.md" index fa42e1ba..cb056d53 100644 --- "a/Build a YeBot with OpenAI API/2. WTH is OpenAI/3. Let\342\200\231s Play with OpenAI Playground Like a Pro.md" +++ "b/Build a YeBot with OpenAI API/2. WTH is OpenAI/3. Let\342\200\231s Play with OpenAI Playground Like a Pro.md" @@ -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. From 48d0cb4c39411b74379dbfa1358696075819533a Mon Sep 17 00:00:00 2001 From: Aamna Kamran Date: Fri, 27 Sep 2024 14:51:23 +0500 Subject: [PATCH 2/3] build the ye bot lesson complete --- .../Building the YeBot!.md" | 44 ++--- .../Connect this Yeezy to a NextJS app.md" | 169 +++++++++--------- 2 files changed, 98 insertions(+), 115 deletions(-) diff --git "a/Build a YeBot with OpenAI API/3. Let\342\200\231s Build Some Dope Shit/Building the YeBot!.md" "b/Build a YeBot with OpenAI API/3. Let\342\200\231s Build Some Dope Shit/Building the YeBot!.md" index 8803db1f..b74dc749 100644 --- "a/Build a YeBot with OpenAI API/3. Let\342\200\231s Build Some Dope Shit/Building the YeBot!.md" +++ "b/Build a YeBot with OpenAI API/3. Let\342\200\231s Build Some Dope Shit/Building the YeBot!.md" @@ -7,46 +7,36 @@ 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 - -First things first! Let’s setup our development environment and learn what the hell is MindsDB. - -## What is MindsDB? - -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. - -## Why MindsDB for YeAI development, you ask? - -- 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! +## What is NextJS? -## Setting up the Development Environment on MindsDB Cloud +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: -Here's how to set up the development environment on MindsDB Cloud: +- Next.js is a React-based framework for building web applications. +- It's a server-side rendering framework, which means it can generate HTML on the server before it's sent to the client. +- It uses automatic code splitting and lazy loading, which means your app loads faster and is more performant. +- It has built-in support for SEO optimization, so your app can be easily discovered by search engines. +- It's flexible and customizable, so you can build your app exactly the way you want it. -- **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). +## So, why use Next.js for building a YeAI bot? -MindsDB editor looks like this: +Here are a few reasons: -![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) +- 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! -Now that we have setup the MindsDB, we will learn how to run our model in MindsDB in the next lesson. +> **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. +> -Get ready for some serious fun with this project, y'all! +Let’s get started and build dope stuff! diff --git "a/Build a YeBot with OpenAI API/3. Let\342\200\231s Build Some Dope Shit/Connect this Yeezy to a NextJS app.md" "b/Build a YeBot with OpenAI API/3. Let\342\200\231s Build Some Dope Shit/Connect this Yeezy to a NextJS app.md" index 49d928c2..0e9419f4 100644 --- "a/Build a YeBot with OpenAI API/3. Let\342\200\231s Build Some Dope Shit/Connect this Yeezy to a NextJS app.md" +++ "b/Build a YeBot with OpenAI API/3. Let\342\200\231s Build Some Dope Shit/Connect this Yeezy to a NextJS app.md" @@ -1,4 +1,4 @@ -# 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. ## 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 @@ -71,7 +73,7 @@ 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); @@ -79,106 +81,97 @@ function iMessage() { 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 ( <> - - - Kanye West Chatbot - Metaschool - - - -
-
- -
- Profile -

YeGPT

-
- -
-
-

Powered by metaschool 🔮

- {messages.map((message, index) => ( -
- {message.user ? ( - <> -
-
{message.text}
-
- User Profile - - ) : ( - <> - Bot Profile - {message.text === 'loading' ? :
-
{message.text}
-
} - - )} -
- ))} + + Kanye West Chatbot + + +
+
+ +
+ Profile +

YeGPT

+
+ +
+
+

Powered by metaschool 🔮

+ {messages.map((message, index) => ( +
+ {message.user ? ( + <> +
+
{message.text}
+
+ User Profile + + ) : ( + <> + Bot Profile + {message.text === 'loading' ? :
+
{message.text}
+
} + + )}
-
- - -
+ ))}
+
+ + +
+
); } -export default iMessage; +export default ChatBot; ``` ### Explanation From dd32515999e81fc012cd0c5a09a405ed6012e1e9 Mon Sep 17 00:00:00 2001 From: Aamna Kamran Date: Fri, 27 Sep 2024 17:30:10 +0500 Subject: [PATCH 3/3] All done - except: 1. adding an image reference in Let's Try our Yeezy Boy 2. changing lesson names --- .../Building the YeBot!.md" | 110 ++++++++++++++++-- 1 file changed, 99 insertions(+), 11 deletions(-) diff --git "a/Build a YeBot with OpenAI API/3. Let\342\200\231s Build Some Dope Shit/Building the YeBot!.md" "b/Build a YeBot with OpenAI API/3. Let\342\200\231s Build Some Dope Shit/Building the YeBot!.md" index b74dc749..17a045a7 100644 --- "a/Build a YeBot with OpenAI API/3. Let\342\200\231s Build Some Dope Shit/Building the YeBot!.md" +++ "b/Build a YeBot with OpenAI API/3. Let\342\200\231s Build Some Dope Shit/Building the YeBot!.md" @@ -17,19 +17,9 @@ We’ll be using code and prompts to build our YeBot, with the OpenAI engine as **Don’t Worry**! We will explain everything one-by-one. So, let’s buckle up to learn and build! -## What is NextJS? - -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: - -- Next.js is a React-based framework for building web applications. -- It's a server-side rendering framework, which means it can generate HTML on the server before it's sent to the client. -- It uses automatic code splitting and lazy loading, which means your app loads faster and is more performant. -- It has built-in support for SEO optimization, so your app can be easily discovered by search engines. -- It's flexible and customizable, so you can build your app exactly the way you want it. - ## So, why use Next.js for building a YeAI bot? -Here are a few reasons: +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. @@ -40,3 +30,101 @@ Here are a few reasons: > 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. + +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. + +6. Error handling: Catches and logs any errors that occur during the API request process. + +## Create a .env file + +Create a new file by the name `.env` and paste this: + +`OPENAI_API_KEY=` + +Be sure to replace the placeholder (``) with the API key you generateed in the previous chapter. + +### But why do we need a .env file? + +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. + +## Let's run the code + +Run this command in your terminal: + +`node chatbot.js` + +Boom! There it is. Just like that. Magic, no cap.