Generative AI (Gen AI) has become a cornerstone of innovation in modern application development. By leveraging models like GPT (Generative Pre-trained Transformer), developers can build applications capable of generating human-like text, creating images, summarizing content, and much more. Integrating Generative AI with a MERN (MongoDB, Express, React, Node.js) stack application can enhance user experiences by adding intelligent automation, conversational interfaces, or creative content generation capabilities. This blog will guide you through the process of integrating Gen AI with a MERN application, focusing on practical implementation.
Before integrating Generative AI into your MERN application, ensure you have:
The backend (Node.js Express) will act as a bridge between your MERN app and the Generative AI API.
npm install express dotenv axios cors
Store your API key securely using a .env file:
npm install express dotenv axios cors
Create a file named server.js or similar and set up the Express server:
OPENAI_API_KEY=your_openai_api_key_here
Use axios or fetch to call your backend API from the React frontend. Install axios if you haven’t already:
const express = require('express'); const axios = require('axios'); const cors = require('cors'); require('dotenv').config(); const app = express(); app.use(express.json()); app.use(cors()); const PORT = 5000; app.post('/api/generate', async (req, res) => { const { prompt } = req.body; try { const response = await axios.post( 'https://api.openai.com/v1/completions', { model: 'text-davinci-003', // Adjust model based on your use case prompt, max_tokens: 100, }, { headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${process.env.OPENAI_API_KEY}`, }, } ); res.status(200).json({ result: response.data.choices[0].text }); } catch (error) { console.error(error); res.status(500).json({ error: 'Failed to generate response' }); } }); app.listen(PORT, () => { console.log(`Server is running on http://localhost:${PORT}`); });
Create a React component to interact with the backend:
npm install axios
import React, { useState } from 'react'; import axios from 'axios'; const AIChat = () => { const [prompt, setPrompt] = useState(''); const [response, setResponse] = useState(''); const [loading, setLoading] = useState(false); const handleSubmit = async (e) => { e.preventDefault(); setLoading(true); try { const result = await axios.post('http://localhost:5000/api/generate', { prompt }); setResponse(result.data.result); } catch (error) { console.error('Error fetching response:', error); setResponse('Error generating response.'); } finally { setLoading(false); } }; return ( <div> <h1>Generative AI Chat</h1> <form onSubmit={handleSubmit}> <textarea value={prompt} onChange={(e) => setPrompt(e.target.value)} placeholder="Enter your prompt here" rows="5" cols="50" /> <br /> <button type="submit" disabled={loading}> {loading ? 'Generating...' : 'Generate'} </button> </form> {response && ( <div> <h3>Response:</h3> <p>{response}</p> </div> )} </div> ); }; export default AIChat;
node server.js
The above is the detailed content of Integrating Generative AI with MERN Applications. For more information, please follow other related articles on the PHP Chinese website!