DEV Community

Cover image for Integrating AI into Your Website: A Step-by-Step Guide with ReactJS and OpenAI
limacodes
limacodes

Posted on

Integrating AI into Your Website: A Step-by-Step Guide with ReactJS and OpenAI

Integrating AI into your website can significantly enhance user experience, especially when dealing with customer support.

In this article, we will walk you through the process of integrating OpenAI’s latest model into a Next.js React application to create an intelligent FAQ hub for a support company.

This AI will be trained with a prompt and use external sources as knowledge bases to provide accurate and relevant answers.

Step 1: Setting Up the Project

First, we need to set up our Next.js application. If you don’t have Next.js installed, you can create a new project by running:

npx create-next-app@latest faq-hub
cd faq-hub

Next, install the necessary dependencies:

npm install openai react-markdown

Step 2: Configuring the OpenAI API

To interact with OpenAI’s API, you need an API key. Sign up on the OpenAI website if you haven’t already and obtain your API key from the dashboard.

Create a file named .env.local in the root of your project to store your API key:

NEXT_PUBLIC_OPENAI_API_KEY=your_openai_api_key_here

Step 3: Creating the AI Service

Create a new directory called services and inside it, create a file named openai.js. This file will contain the function to interact with the OpenAI API:

// services/openai.js
export async function fetchOpenAIResponse(prompt) {
const response = await fetch('https://api.openai.com/v1/completions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': Bearer ${process.env.NEXT_PUBLIC_OPENAI_API_KEY},
},
body: JSON.stringify({
model: 'text-davinci-003', // Replace with the latest model
prompt: prompt,
max_tokens: 150,
}),
});
const data = await response.json();
return data.choices[0].text.trim();
}

Step 4: Building the FAQ Component

Now, let’s create a React component to display the FAQ section. Create a new directory called components and inside it, create a file named FAQHub.js:

// components/FAQHub.js
import React, { useState } from 'react';
import { fetchOpenAIResponse } from '../services/openai';
import ReactMarkdown from 'react-markdown';
const FAQHub = () => {
const [query, setQuery] = useState('');
const [response, setResponse] = useState('');
const handleInputChange = (e) => {
setQuery(e.target.value);
};
const handleSubmit = async (e) => {
e.preventDefault();
const aiResponse = await fetchOpenAIResponse(query);
setResponse(aiResponse);
};
return (
<div>
<h1>FAQ Hub</h1>
<form onSubmit={handleSubmit}>
<input
type="text"
value={query}
onChange={handleInputChange}
placeholder="Ask a question..."
/>
<button type="submit">Get Answer</button>
</form>
<div>
<ReactMarkdown>{response}</ReactMarkdown>
</div>
</div>
);
};
export default FAQHub;

Step 5: Integrating the FAQ Component into the Next.js Application

Open the pages/index.js file and import the FAQHub component:

// pages/index.js
import FAQHub from '../components/FAQHub';
export default function Home() {
return (
<div>
<FAQHub />
</div>
);
}

Step 6: Training the Model with a Prompt and External Sources

To enhance the model’s responses, you can prime it with a specific prompt and leverage external knowledge bases. Here’s an example of how you can modify the fetchOpenAIResponse function to include a custom prompt:

// services/openai.js
export async function fetchOpenAIResponse(query) {
const prompt =
You are a highly intelligent FAQ bot. Answer the following question based on the knowledge from our support database and external sources:
Question: ${query};
const response = await fetch('https://api.openai.com/v1/completions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization':
Bearer ${process.env.NEXT_PUBLIC_OPENAI_API_KEY},
},
body: JSON.stringify({
model: 'text-davinci-003', // Replace with the latest model
prompt: prompt,
max_tokens: 150,
}),
});
const data = await response.json();
return data.choices[0].text.trim();
}

Step 7: Deploying the Application

Once you have tested the application locally and ensured everything works as expected, you can deploy your Next.js application to platforms like Vercel or Netlify.

Deploy to Vercel
If you choose Vercel, you can deploy your application with the following commands:

npm install -g vercel
vercel

Follow the prompts to link your project and deploy it.

Conclusion

Congratulations! You have successfully integrated OpenAI into your Next.js React application to create an intelligent FAQ hub. By leveraging AI, you can provide users with accurate and dynamic responses to their queries, enhancing their support experience. Remember to keep your API keys secure and monitor usage to avoid unauthorized access and potential abuse.

Happy coding!

Top comments (0)