In this article, we will walk through the step-by-step implementation of an AI Text Analysis App using React, Vite, and OpenAI’s GPT-3.5. This app will allow users to input text and analyze it for sentiment, topics, summary, and language detection. By the end of this guide, even beginners will be able to build and understand this application. We will also explain each feature in detail and provide examples to ensure clarity.
Introduction
The AI Text Analysis App is a powerful tool that leverages OpenAI’s GPT-3.5 to analyze text. It provides insights into the emotional tone of the text (sentiment), identifies the main topics, generates a concise summary, and detects the language of the input text. This app is built using React for the front end, Vite for fast development, and Tailwind CSS for styling.
Step 1: Setting Up the Project
Create a New React App With Vite
We will use Vite to create a new React app because it is fast and modern.
- Launch your terminal and execute the command below. During the project initialization, select React as the framework and configure it to use
TypeScript
for type-safe development.npm create vite@latest ai-text-analysis-app
- Navigate to the project directory:
cd ai-text-analysis-app
- Install the dependencies:
npm install
Install Required Dependencies
Let’s add some extra packages required to enhance the app’s functionality:
- Tailwind CSS: For styling the app.
- Lucide React: For icons.
- OpenAI: To interact with the OpenAI API.
Execute the command below to install the required packages for this project:npm install tailwindcss postcss autoprefixer lucide-react openai
Set Up Tailwind CSS
1. Initialize Tailwind CSS:npx tailwindcss init -p
2. Open the tailwind.config.js
file and configure it to include all necessary files:
export default {
content: [
"./index.html",
"./src/**/*.{js,ts,jsx,tsx}",
],
theme: {
extend: {},
},
plugins: [],
}
3. Navigate to the src/index.css
file and overwrite its contents with the code below:
@tailwind base;
@tailwind components;
@tailwind utilities;
Step 2: Create the OpenAI Service
Set Up OpenAI API Key
- Create a .env file in the root of your project:
VITE_OPENAI_API_KEY=your_openai_api_key_here
- Replace
your_openai_api_key_here
with your actual OpenAI API key. - Add the .
env
file to your.gitignore
to avoid committing sensitive information:.env
Create the OpenAI Service
Create a new folder src/services
and add a file named openai.ts
:
import OpenAI from 'openai';
import { AnalysisResult, AIError } from '../types/ai';
const openai = new OpenAI({
apiKey: import.meta.env.VITE_OPENAI_API_KEY,
dangerouslyAllowBrowser: true
});
export async function analyzeText(text: string): Promise {
try {
const response = await openai.chat.completions.create({
model: "gpt-3.5-turbo",
messages: [{
role: "system",
content: "Analyze the following text and provide sentiment, main topics, a brief summary, and detected language. Return as JSON."
}, {
role: "user",
content: text
}],
response_format: { type: "json_object" }
});
return JSON.parse(response.choices[0].message?.content || '{}');
} catch (error) {
throw {
message: 'Failed to analyze text',
code: error instanceof Error ? error.message : 'UNKNOWN_ERROR'
} as AIError;
}
}
This service sends the user’s text to OpenAI’s GPT-3.5 model and returns the analysis result.
Step 3: Define Types
Create Type Definitions
Create a new folder src/types and add a file named ai.ts
:
export interface AnalysisResult {
sentiment: string;
topics: string[];
summary: string;
language: string;
}
export interface AIError {
message: string;
code?: string;
}
These types define the structure of the analysis result and error objects.
Step 4: Build the Components
TextInput Component
This component allows users to input text and submit it for analysis.
Within your project structure, generate a src/components
directory and populate it with a TextInput.tsx
file to house the component logic.
import React from 'react';
import { Send } from 'lucide-react';
interface TextInputProps {
value: string;
onChange: (value: string) => void;
onSubmit: () => void;
isLoading: boolean;
}
export function TextInput({ value, onChange, onSubmit, isLoading }: TextInputProps) {
return (
);
}
AnalysisResult Component
This component displays the analysis result.
Create a file named AnalysisResult.tsx
in the src/components
folder:
import React from 'react';
import { Brain, List, MessageSquare, Globe } from 'lucide-react';
import { AnalysisResult } from '../types/ai';
interface AnalysisResultProps {
result: AnalysisResult;
}
export function AnalysisResultView({ result }: AnalysisResultProps) {
return (
Sentiment
{result.sentiment}
Topics
{result.topics.map((topic, index) => (
- {topic}
))}
Language
{result.language}
);
}
ErrorMessage Component
This component displays errors.
Create an ErrorMessage.tsx
file inside the src/components
directory to encapsulate your error display logic.
import React from 'react';
import { AlertCircle } from 'lucide-react';
import { AIError } from '../types/ai';
interface ErrorMessageProps {
error: AIError;
onDismiss: () => void;
}
export function ErrorMessage({ error, onDismiss }: ErrorMessageProps) {
return (
{error.message}
{error.code && (
Error code: {error.code}
)}
);
}
Step 5: Build the Main App Component
import React, { useState } from 'react';
import { TextInput } from './components/TextInput';
import { AnalysisResultView } from './components/AnalysisResult';
import { ErrorMessage } from './components/ErrorMessage';
import { analyzeText } from './services/openai';
import type { AnalysisResult, AIError } from './types/ai';
function App() {
const [text, setText] = useState('');
const [result, setResult] = useState(null);
const [error, setError] = useState(null);
const [isLoading, setIsLoading] = useState(false);
const handleAnalyze = async () => {
setIsLoading(true);
setError(null);
try {
const analysis = await analyzeText(text);
setResult(analysis);
} catch (err) {
setError(err as AIError);
} finally {
setIsLoading(false);
}
};
return (
{error && (
setError(null)}
/>
)}
{isLoading && (
Analyzing text...
)}
{result && !isLoading && (
)}
);
}
export default App;
Step 6: Run the App
- Spin up the development server by executing
npm run dev
in your terminal. - Access the application through your browser at http://localhost:5173.
- Interact with the UI: Type into the input field and hit the Send button to trigger the analysis and view the output results.
FAQ Section
What is Sentiment Analysis?
Sentiment analysis is a Natural Language Processing (NLP) technique that identifies the emotional tone within a body of text. It classifies the input as positive, negative, or neutral, helping systems interpret subjective content.
How does Topic Extraction work?
Topic Extraction identifies the main subjects and themes discussed in the text. It helps in categorizing content and understanding the key points of a document.
What is Text Summarization?
Text Summarization creates concise summaries of longer texts. It is useful for quickly understanding the main points of lengthy documents, articles, or reports.
How is Language Detection useful?
Language Detection identifies the language of the input text. It is useful for multilingual applications where the language of the text needs to be determined before further processing.
Can I use this app for commercial purposes?
Yes, the AI Text Analysis App is licensed under the MIT License, which allows you to use it for both personal and commercial purposes.
How do I get an OpenAI API key?
You can get an OpenAI API key by signing up on the OpenAI website and creating an API key in your account settings.
Is this app secure?
Yes, the app is designed with security in mind. It uses environment variables to store sensitive data like the OpenAI API key and implements error handling to manage API call failures.
Can I customize the app?
Absolutely! The app is built with React and TypeScript, making it easy to customize and extend according to your needs.
By following this guide, you should now have a solid understanding of how to build and use the AI Text Analysis App. Happy coding!
Conclusion
You have successfully built an AI Text Analysis App using React, Vite, and OpenAI’s GPT-3.5. This app analyzes text for sentiment, topics, summary, and language detection. You can now extend this app by adding more features or integrating it into your projects.