How to Use OpenAI API in ReactJS to Create a Text Summarization Tool
Introduction:
In this tutorial, we'll learn how to harness the power of OpenAI's API to create a text summarization tool using ReactJS. By the end of this guide, you'll have a fully functional application that can condense long passages of text into concise summaries. We'll be utilizing Tailwind CSS to style our application and make it visually appealing. So, let's dive in and start building!
Prerequisites:
- Basic knowledge of ReactJS
- Familiarity with HTML and CSS
- An OpenAI API key (learn how to get one here: https://www.youtube.com/watch?v=bPG5d0o4BhU)
Step 1: Setting Up the React Project First, open your terminal and navigate to the directory where you want to create your project. Run the following command to create a new React project with Tailwind CSS:
npx create-react-app my-app cd my-app
1npx create-react-app my-app
2cd my-app
Step 2: Installing and Configuring Tailwind CSS Now, let's install Tailwind CSS as a dev dependency. In your terminal, run:
npm install -D tailwindcss postcss autoprefixer npx tailwindcss init -p
1npm install -D tailwindcss postcss autoprefixer
2npx tailwindcss init -p
Next, replace the contents of your tailwind.config.js
file with the following:
module.exports = { content: [ "./src/**/*.{js,jsx,ts,tsx}", ], theme: { extend: {}, }, plugins: [], }
1module.exports = {
2 content: [
3 "./src/**/*.{js,jsx,ts,tsx}",
4 ],
5 theme: {
6 extend: {},
7 },
8 plugins: [],
9}
Open your src/index.css
file and replace its contents with:
@tailwind base; @tailwind components; @tailwind utilities;
1@tailwind base;
2@tailwind components;
3@tailwind utilities;
Step 3: Creating the User Interface Let's start building our application's user interface. We'll be using pre-built components from Tailwind CSS to speed up the process.
Replace the contents of your src/App.js
file with the following code:
import React, { useState } from 'react' export default function App() { const [content, setContent] = useState('') const [summary, setSummary] = useState('') const summarize = async () => { const apiUrl = 'https://api.openai.com/v1/chat/completions' const apiKey = 'YOUR_API_KEY' const headers = { 'Content-Type': 'application/json', 'Authorization': `Bearer ${apiKey}` } const data = { model: 'gpt-3.5-turbo', messages: [ { role: 'system', content: 'You are a helpful assistant. and you have to summarize the text provided by the user.' }, { role: 'user', content } ] } const response = await fetch(apiUrl, { method: 'POST', headers, body: JSON.stringify(data) }) const result = await response.json() const summary = result.choices[0].message.content setSummary(summary) } return ( <> <header className="text-gray-600 body-font"> <div className="container mx-auto flex flex-wrap p-5 flex-col md:flex-row items-center"> <a href="/" className="flex title-font font-medium items-center text-gray-900 mb-4 md:mb-0"> <span className="ml-3 text-xl">AyyazTech</span> </a> <nav className="md:ml-auto flex flex-wrap items-center text-base justify-center"> <a href="/" className="mr-5 hover:text-gray-900">First Link</a> <a href="/" className="mr-5 hover:text-gray-900">Second Link</a> <a href="/" className="mr-5 hover:text-gray-900">Third Link</a> <a href="/" className="mr-5 hover:text-gray-900">Fourth Link</a> </nav> <button className="inline-flex items-center bg-gray-100 border-0 py-1 px-3 focus:outline-none hover:bg-gray-200 rounded text-base mt-4 md:mt-0">Button </button> </div> </header> <section className="text-gray-600 body-font relative"> <div className="container px-5 py-24 mx-auto"> <div className="flex flex-col text-center w-full mb-12"> <h1 className="sm:text-3xl text-2xl font-medium title-font mb-4 text-gray-900">AI Summarization Tool</h1> <p className="lg:w-2/3 mx-auto leading-relaxed text-base"> This is a simple AI summarization tool that can summarize any text into a few sentences. Just paste the text in the box below and click the button to get the summary. </p> </div> <div className="lg:w-1/2 md:w-2/3 mx-auto"> <div className="flex flex-wrap -m-2"> <div className="p-2 w-full"> <div className="relative"> <label htmlFor="message" className="leading-7 text-sm text-gray-600">Content</label> <textarea value={content} onChange={e => setContent(e.target.value)} id="message" name="message" className="w-full bg-gray-100 bg-opacity-50 rounded border border-gray-300 focus:border-indigo-500 focus:bg-white focus:ring-2 focus:ring-indigo-200 h-32 text-base outline-none text-gray-700 py-1 px-3 resize-none leading-6 transition-colors duration-200 ease-in-out"></textarea> </div> </div> <div className="p-2 w-full"> <button onClick={summarize} className="flex mx-auto text-white bg-indigo-500 border-0 py-2 px-8 focus:outline-none hover:bg-indigo-600 rounded text-lg">Summarize</button> </div> </div> </div> </div> </section> {/* Summary */} <hr /> <section className="text-gray-600 body-font"> <div className="container px-5 py-24 mx-auto"> <div className="flex flex-col text-center w-full mb-20"> <h1 className="sm:text-3xl text-2xl font-medium title-font mb-4 text-gray-900">Summary</h1> <p className="lg:w-2/3 mx-auto leading-relaxed text-base"> {summary} </p> </div> </div> </section> </> ) }
1import React, { useState } from 'react'
2
3export default function App() {
4
5 const [content, setContent] = useState('')
6 const [summary, setSummary] = useState('')
7
8
9 const summarize = async () => {
10 const apiUrl = 'https://api.openai.com/v1/chat/completions'
11 const apiKey = 'YOUR_API_KEY'
12 const headers = {
13 'Content-Type': 'application/json',
14 'Authorization': `Bearer ${apiKey}`
15 }
16
17 const data = {
18 model: 'gpt-3.5-turbo',
19 messages: [
20 { role: 'system', content: 'You are a helpful assistant. and you have to summarize the text provided by the user.' },
21 { role: 'user', content }
22 ]
23 }
24
25 const response = await fetch(apiUrl, {
26 method: 'POST',
27 headers,
28 body: JSON.stringify(data)
29 })
30
31 const result = await response.json()
32 const summary = result.choices[0].message.content
33
34 setSummary(summary)
35
36 }
37
38 return (
39 <>
40 <header className="text-gray-600 body-font">
41 <div className="container mx-auto flex flex-wrap p-5 flex-col md:flex-row items-center">
42 <a href="/" className="flex title-font font-medium items-center text-gray-900 mb-4 md:mb-0">
43
44 <span className="ml-3 text-xl">AyyazTech</span>
45 </a>
46 <nav className="md:ml-auto flex flex-wrap items-center text-base justify-center">
47 <a href="/" className="mr-5 hover:text-gray-900">First Link</a>
48 <a href="/" className="mr-5 hover:text-gray-900">Second Link</a>
49 <a href="/" className="mr-5 hover:text-gray-900">Third Link</a>
50 <a href="/" className="mr-5 hover:text-gray-900">Fourth Link</a>
51 </nav>
52 <button
53
54 className="inline-flex items-center bg-gray-100 border-0 py-1 px-3 focus:outline-none hover:bg-gray-200 rounded text-base mt-4 md:mt-0">Button
55
56 </button>
57 </div>
58</header>
59
60
61
62<section className="text-gray-600 body-font relative">
63 <div className="container px-5 py-24 mx-auto">
64 <div className="flex flex-col text-center w-full mb-12">
65 <h1 className="sm:text-3xl text-2xl font-medium title-font mb-4 text-gray-900">AI Summarization Tool</h1>
66 <p className="lg:w-2/3 mx-auto leading-relaxed text-base">
67 This is a simple AI summarization tool that can summarize any text into a few sentences. Just paste the text in the box below and click the button to get the summary.
68 </p>
69 </div>
70 <div className="lg:w-1/2 md:w-2/3 mx-auto">
71 <div className="flex flex-wrap -m-2">
72
73 <div className="p-2 w-full">
74 <div className="relative">
75 <label htmlFor="message" className="leading-7 text-sm text-gray-600">Content</label>
76 <textarea
77 value={content}
78 onChange={e => setContent(e.target.value)}
79 id="message" name="message" className="w-full bg-gray-100 bg-opacity-50 rounded border border-gray-300 focus:border-indigo-500 focus:bg-white focus:ring-2 focus:ring-indigo-200 h-32 text-base outline-none text-gray-700 py-1 px-3 resize-none leading-6 transition-colors duration-200 ease-in-out"></textarea>
80 </div>
81 </div>
82 <div className="p-2 w-full">
83 <button onClick={summarize} className="flex mx-auto text-white bg-indigo-500 border-0 py-2 px-8 focus:outline-none hover:bg-indigo-600 rounded text-lg">Summarize</button>
84 </div>
85
86 </div>
87 </div>
88 </div>
89</section>
90
91 {/* Summary */}
92<hr />
93<section className="text-gray-600 body-font">
94 <div className="container px-5 py-24 mx-auto">
95 <div className="flex flex-col text-center w-full mb-20">
96 <h1 className="sm:text-3xl text-2xl font-medium title-font mb-4 text-gray-900">Summary</h1>
97 <p className="lg:w-2/3 mx-auto leading-relaxed text-base">
98 {summary}
99 </p>
100 </div>
101 </div>
102</section>
103
104 </>
105 )
106}
Step 4: Integrating the OpenAI API Now, let's connect our application with the OpenAI API to generate the summaries. Add the following code inside the handleSummarize
function:
const apiKey = 'YOUR_API_KEY'; const url = 'https://api.openai.com/v1/chat/completions'; const headers = { 'Content-Type': 'application/json', 'Authorization': `Bearer ${apiKey}`, }; const data = { model: 'gpt-3.5-turbo', messages: [ { role: 'system', content: 'You are a helpful assistant that summarizes text.' }, { role: 'user', content: content }, ], }; fetch(url, { method: 'POST', headers: headers, body: JSON.stringify(data), }) .then((response) => response.json()) .then((data) => { const summary = data.choices[0].message.content; setSummary(summary); }) .catch((error) => { console.error('Error:', error); });
1const apiKey = 'YOUR_API_KEY';
2const url = 'https://api.openai.com/v1/chat/completions';
3
4const headers = {
5 'Content-Type': 'application/json',
6 'Authorization': `Bearer ${apiKey}`,
7};
8
9const data = {
10 model: 'gpt-3.5-turbo',
11 messages: [
12 { role: 'system', content: 'You are a helpful assistant that summarizes text.' },
13 { role: 'user', content: content },
14 ],
15};
16
17fetch(url, {
18 method: 'POST',
19 headers: headers,
20 body: JSON.stringify(data),
21})
22 .then((response) => response.json())
23 .then((data) => {
24 const summary = data.choices[0].message.content;
25 setSummary(summary);
26 })
27 .catch((error) => {
28 console.error('Error:', error);
29 });
30
Make sure to replace 'YOUR_API_KEY'
with your actual OpenAI API key.
Step 5: Testing the Summarization Tool Start your React application by running npm start
in your terminal. Open your browser and navigate to http://localhost:3000
. You should see your summarization tool up and running!
Try pasting a long passage of text into the text area and click the "Summarize" button. The OpenAI API will process the text and generate a concise summary, which will be displayed below.
Conclusion: Congratulations! You've successfully created a text summarization tool using ReactJS and the OpenAI API. This tutorial demonstrates the power of combining AI with web development to create useful applications.
If you found this video helpful, please consider subscribing to my YouTube channel for more exciting content. Don't forget to like, share, and leave a comment with your thoughts or suggestions for future videos.
Happy coding!
Related Videos:
- From Coders to Creatives: 9 Must-See Uses of ChatGPT 4 Vision! (https://www.youtube.com/watch?v=qN9CiYmfQIM)
- React & Tailwind CSS: Crafting a Quiz App Guided by ChatGPT 4 (https://www.youtube.com/watch?v=-Y_khYHLTr4)
- React & Tailwind CSS: Crafting a Quick Image Editor Guided by ChatGPT (https://www.youtube.com/watch?v=14-Bkt17i1M)
GITHUB Repo: https://github.com/ayyazzafar/reactjs_17_tutorials_code