AI & prompting / 2 MIN READ
React ChatGPT
Build a ChatGPT-powered chat interface using React
From the original Fervor library. Examples may use older package versions.
Let’s create a simple React component that interacts with the ChatGPT 3.5 Turbo API to send queries and display responses. This tutorial will guide you through creating a basic chat interface. Before we start, make sure you have React environment set up and an OpenAI API key.
Step 1: Set Up Your React App
If you haven’t already, create a new React app:
npx create-react-app chatgpt-app
cd chatgpt-app
Install Axios for making HTTP requests:
npm install axios
Step 2: Get Your OpenAI API Key
You’ll need an API key from OpenAI. If you don’t have one:
- Go to OpenAI and sign up or log in.
- Navigate to the API section and generate an API key.
Step 3: Create the Chat Component
Create a new file in your src directory named ChatGPTChat.js. This is where we’ll build our chat interface.
import React, { useState } from 'react';
import axios from 'axios';
const ChatGPTChat = () => {
const [query, setQuery] = useState('');
const [responses, setResponses] = useState([]);
const handleInputChange = (event) => {
setQuery(event.target.value);
};
const handleSubmit = async (event) => {
event.preventDefault();
if (!query) return;
try {
const response = await axios.post('https://api.openai.com/v1/completions', {
model: "gpt-3.5-turbo",
prompt: query,
temperature: 0.5,
max_tokens: 100,
}, {
headers: {
'Authorization': `Bearer YOUR_API_KEY_HERE`
}
});
setResponses(oldResponses => [...oldResponses, { query, response: response.data.choices[0].text }]);
setQuery(''); // Clear the input after sending the query
} catch (error) {
console.error('Error calling OpenAI API:', error);
}
};
return (
<div>
<form onSubmit={handleSubmit}>
<input type="text" value={query} onChange={handleInputChange} />
<button type="submit">Send</button>
</form>
<div>
{responses.map((entry, index) => (
<div key={index}>
<p><strong>You:</strong> {entry.query}</p>
<p><strong>GPT:</strong> {entry.response}</p>
</div>
))}
</div>
</div>
);
};
export default ChatGPTChat;
Step 4: Update Your API Key
Replace YOUR_API_KEY_HERE with your actual OpenAI API key.
Step 5: Add the Component to Your App
Open src/App.js and use the ChatGPTChat component:
import React from 'react';
import './App.css';
import ChatGPTChat from './ChatGPTChat';
function App() {
return (
<div className="App">
<header className="App-header">
<ChatGPTChat />
</header>
</div>
);
}
export default App;
Step 6: Run Your App
Start your application:
npm start
Your browser should open to localhost:3000, displaying your simple chat interface with ChatGPT 3.5 Turbo API.
Done!
And there you have it—a simple chat interface using React and the ChatGPT 3.5 Turbo API. Remember, this is a basic implementation. Explore more to enhance functionalities like adding loading states, error handling, and styling to make your chat app even cooler!