AI bilen işleýän söhbetdeşlikler ulanyjy tejribesini ýokarlandyryp we jogaplary netijeli awtomatlaşdyryp biler. Bu gollanmada, “Express” -iň arkasy bilen integrasiýa bilen “React” , “Vite” we “Cohere” API ulanyp, chatboty nädip gurmalydygyny öwrenersiňiz. Vite ýönekeýligi we tizligi bilen häzirki zaman JavaScript programmalaryny gurmagy aňsatlaşdyrýar.
Bu arhitektura, serwer arkaly haýyşlary ugrukdyrmak arkaly duýgur API düwmeleriniň açylmagynyň öňüni alýar.
“Vite” ulanyp, täze “React” taslamasyny dörediň:
npm create vite@latest ai-chatbot -- --template react cd ai-chatbot npm install
Ösüş serwerine başlaň:
npm run dev
Şol bir katalogda täze Node.js taslamasyny başlaň:
mkdir server && cd server npm init -y
Gerekli paketleri guruň:
npm install express cors dotenv node-fetch
Nativeerli importdan peýdalanmak üçin görnüş module
ulanmak üçin package.json faýly täzeläň:
{ "name": "server", "version": "1.0.0", "description": "", "main": "index.js", "type": "module", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "", "license": "ISC", "dependencies": { "cors": "^2.8.5", "dotenv": "^16.4.7", "express": "^4.21.2", "node-fetch": "^3.3.2" } }
server
katalogynda server.js
atly bir faýl dörediň we aşakdaky kody goşuň:
import 'dotenv/config' import express from 'express'; import cors from 'cors'; import fetch from 'node-fetch'; const app = express(); const PORT = 5000; app.use(cors()); app.use(express.json()); app.post('/generate', async (req, res) => { const { prompt } = req.body; if (!prompt) { return res.status(400).json({ error: 'Prompt is required' }); } try { const response = await fetch('https://api.cohere.ai/v1/generate', { method: 'POST', headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${process.env.COHERE_API_KEY}`, }, body: JSON.stringify({ model: 'command-xlarge-nightly', prompt: `User: ${prompt}\nBot:`, max_tokens: 100, }), }); const data = await response.json(); res.json(data.generations[0].text.trim()); } catch (error) { console.error('Error calling Cohere API:', error); res.status(500).json({ error: 'Failed to generate response' }); } }); app.listen(PORT, () => { console.log(`Server running on http://localhost:${PORT}`); });
server
katalogynda .env
faýly dörediň:
COHERE_API_KEY=your_cohere_api_key_here
Serweri işe giriziň:
node server.js
Üns beriň: .env
faýlyňyzy hiç haçan paýlaşmaň ýa-da wersiýa gözegçilik etmäň. .gitignore
faýlyňyza .env
goşuň.
App.jsx
faýlyny aşakdaky kod bilen täzeläň:
import React, { useState } from 'react'; import './App.css'; const App = () => { const [messages, setMessages] = useState([]); const [userInput, setUserInput] = useState(''); const [loading, setLoading] = useState(false); const sendMessage = async () => { if (!userInput.trim()) return; const newMessages = [...messages, { sender: 'user', text: userInput }]; setMessages(newMessages); setUserInput(''); setLoading(true); try { const response = await fetch('http://localhost:5000/generate', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ prompt: userInput }), }); const botReply = await response.text(); setMessages([...newMessages, { sender: 'bot', text: botReply }]); } catch (error) { console.error('Error fetching bot reply:', error); setMessages([ ...newMessages, { sender: 'bot', text: 'Sorry, something went wrong.' }, ]); } finally { setLoading(false); } }; return ( <div className="chat-container"> <div className="chatbox"> {messages.map((msg, index) => ( <div key={index} className={`message ${msg.sender}`}> {msg.text} </div> ))} {loading && <div className="message bot">Typing...</div>} </div> <div className="input-container"> <input type="text" value={userInput} onChange={(e) => setUserInput(e.target.value)} placeholder="Type your message..." /> <button onClick={sendMessage}>Send</button> </div> </div> ); }; export default App;
Chatbot interfeýsini düzmek üçin App.css
atly bir faýl dörediň:
code.chat-container { font-family: Arial, sans-serif; max-width: 500px; margin: 20px auto; } .chatbox { border: 1px solid #ccc; padding: 10px; height: 400px; overflow-y: auto; border-radius: 5px; margin-bottom: 10px; } .message { margin: 5px 0; padding: 10px; border-radius: 5px; } .message.user { background-color: #d1e7dd; text-align: right; } .message.bot { background-color: #f8d7da; text-align: left; } .input-container { display: flex; } input { flex: 1; padding: 10px; border: 1px solid #ccc; border-radius: 5px 0 0 5px; } button { padding: 10px; border: 1px solid #ccc; border-radius: 0 5px 5px 0; background-color: #007bff; color: white; cursor: pointer; }
Terminal 1:
npm run dev
Terminal 2 ( server
içinde):
node server.js
Bu taslama üçin doly çeşme koduny GitHub: AI Chatbot bilen React we Cohere tapyp bilersiňiz. Ony klonlamak, kody öwrenmek we zerurlyklaryňyza görä düzmek üçin arkaýyn boluň!
“React” , “Vite” , “Cohere” we “Express” ulanyp, “AI” bilen işleýän chatbot gurduňyz. Bu taslama aşakdaky ýaly aýratynlyklar bilen ösdürilip bilner:
Synag we bagtly kodlamaga başlaň!