الدمج مع الويب
إنشاء تطبيق ويب باستخدام ChatGPT
10-15 دقيقة
دمج ChatGPT في تطبيق ويب
البنية الأساسية
لدمج ChatGPT في تطبيق ويب، سنعتمد بنية العميل والخادم (client-server):
Client (Frontend) <-> Serveur (Backend) <-> API ChatGPT
هيكل المشروع
chatgpt-app/
├── frontend/
│ ├── src/
│ │ ├── components/
│ │ ├── services/
│ │ └── styles/
│ ├── package.json
│ └── index.html
├── backend/
│ ├── src/
│ │ ├── controllers/
│ │ ├── services/
│ │ └── config/
│ ├── package.json
│ └── .env
└── README.md
الواجهة الخلفية (Node.js/Express)
إعداد الخادم
// 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
// 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();
التعليقات
التعليقات مدعومة عبر GitHub Discussions
سجّل الدخول باستخدام GitHub للمشاركة في النقاش