Web Integration
Building a web application with ChatGPT
10-15 min
Integrating ChatGPT into a Web Application
Basic Architecture
To integrate ChatGPT into a web application, we will use a client-server architecture:
Client (Frontend) <-> Server (Backend) <-> ChatGPT API
Project Structure
chatgpt-app/
├── frontend/
│ ├── src/
│ │ ├── components/
│ │ ├── services/
│ │ └── styles/
│ ├── package.json
│ └── index.html
├── backend/
│ ├── src/
│ │ ├── controllers/
│ │ ├── services/
│ │ └── config/
│ ├── package.json
│ └── .env
└── README.md
Backend (Node.js/Express)
Server Configuration
// backend/src/config/config.js
require('dotenv').config();
module.exports = {
port: process.env.PORT || 3000,
openaiApiKey: process.env.OPENAI_API_KEY,
corsOrigin: process.env.CORS_ORIGIN || 'http://localhost:5173'
};
ChatGPT Service
// backend/src/services/chatgpt.service.js
const { Configuration, OpenAIApi } = require('openai');
const config = require('../config/config');
const configuration = new Configuration({
apiKey: config.openaiApiKey,
});
const openai = new OpenAIApi(configuration);
class ChatGPTService {
async generateResponse(prompt, context = []) {
try {
const completion = await openai.createChatCompletion({
model: "gpt-3.5-turbo",
messages: [
{ role: "system", content: "Vous êtes un assistant utile et amical." },
...context,
{ role: "user", content: prompt }
],
temperature: 0.7,
max_tokens: 500
});
return completion.data.choices[0].message.content;
} catch (error) {
console.error('Erreur ChatGPT:', error);
throw new Error('Erreur lors de la génération de la réponse');
}
}
}
module.exports = new ChatGPTService();
Comments
Comments are powered by GitHub Discussions
Sign in with GitHub to join the discussion