以下是一个基于React前端 + Node.js(Express)后端的智能体系统实现方案,包含详细代码和运行说明:
一、前端部分(使用React)
-
创建项目:
bash
复制
npx create-react-app ai-agent-frontend cd ai-agent-frontend
-
修改src/App.js:
jsx
复制
import React, { useState } from 'react'; import axios from 'axios'; import './App.css';function App() {const [input, setInput] = useState('');const [messages, setMessages] = useState([]);const handleSubmit = async (e) => {e.preventDefault();if (!input.trim()) return;// 添加用户消息setMessages(prev => [...prev, { text: input, isBot: false }]);try {const response = await axios.post('http://localhost:5000/api/chat', {message: input});// 添加AI回复setMessages(prev => [...prev, { text: response.data.reply, isBot: true }]);} catch (error) {console.error('Error:', error);setMessages(prev => [...prev, { text: '抱歉,服务暂时不可用', isBot: true }]);}setInput('');};return (<div className="app"><div className="chat-container"><div className="messages">{messages.map((msg, index) => (<div key={index} className={`message ${msg.isBot ? 'bot' : 'user'}`}>{msg.text}</div>))}</div><form onSubmit={handleSubmit}><inputtype="text"value={input}onChange={(e) => setInput(e.target.value)}placeholder="输入你的消息..."/><button type="submit">发送</button></form></div></div>); }export default App;
-
修改src/App.css:
css
复制
.app {display: flex;justify-content: center;padding: 20px;min-height: 100vh;background-color: #f0f2f5; }.chat-container {width: 600px;background: white;border-radius: 10px;box-shadow: 0 2px 10px rgba(0,0,0,0.1); }.messages {height: 500px;overflow-y: auto;padding: 20px; }.message {margin: 10px 0;padding: 10px 15px;border-radius: 20px;max-width: 80%; }.user {background: #007bff;color: white;margin-left: auto; }.bot {background: #e9ecef;color: black;margin-right: auto; }form {display: flex;padding: 20px;border-top: 1px solid #ddd; }input {flex: 1;padding: 10px;border: 1px solid #ddd;border-radius: 5px;margin-right: 10px; }button {padding: 10px 20px;background: #007bff;color: white;border: none;border-radius: 5px;cursor: pointer; }button:hover {background: #0056b3; }
安装axios:
bash
复制
npm install axios
二、后端部分(使用Node.js + Express)
-
创建项目:
bash
复制
mkdir ai-agent-backend cd ai-agent-backend npm init -y npm install express cors axios body-parser
-
创建server.js:
javascript
复制
const express = require('express'); const bodyParser = require('body-parser'); const cors = require('cors'); const app = express();// 中间件 app.use(bodyParser.json()); app.use(cors());// 模拟AI回复 function getAIReply(message) {const responses = {'你好': '你好!有什么可以帮您的吗?','天气': '今天是晴天,气温25℃左右。','推荐电影': '推荐您观看《肖申克的救赎》','默认': '我还在学习中,暂时无法回答这个问题。'};return responses[message] || responses['默认']; }// API路由 app.post('/api/chat', (req, res) => {const userMessage = req.body.message;// 模拟处理延迟setTimeout(() => {const reply = getAIReply(userMessage);res.json({ reply });}, 800); });// 启动服务 const PORT = process.env.PORT || 5000; app.listen(PORT, () => {console.log(`Server running on port ${PORT}`); });
三、运行说明
-
启动后端服务:
bash
复制
cd ai-agent-backend node server.js
-
启动前端应用:
bash
复制
cd ai-agent-frontend npm start
-
访问应用:
打开浏览器访问 http://localhost:3000
四、功能扩展建议
-
接入真实AI API:
javascript
复制
// 在server.js中添加: const axios = require('axios');async function getRealAIResponse(message) {try {const response = await axios.post('https://api.openai.com/v1/chat/completions', {model: "gpt-3.5-turbo",messages: [{role: "user", content: message}]}, {headers: {'Authorization': `Bearer ${process.env.OPENAI_API_KEY}`,'Content-Type': 'application/json'}});return response.data.choices[0].message.content;} catch (error) {console.error('API Error:', error);return '抱歉,暂时无法处理您的请求';} }
-
添加数据库支持(使用MongoDB示例):
javascript
复制
// 安装mongoose npm install mongoose// 在server.js中添加: const mongoose = require('mongoose');mongoose.connect('mongodb://localhost:27017/chatDB', {useNewUrlParser: true,useUnifiedTopology: true });const chatSchema = new mongoose.Schema({message: String,response: String,timestamp: { type: Date, default: Date.now } });const Chat = mongoose.model('Chat', chatSchema);// 修改API路由保存数据 app.post('/api/chat', async (req, res) => {const userMessage = req.body.message;const reply = getAIReply(userMessage);const chat = new Chat({message: userMessage,response: reply});await chat.save();res.json({ reply }); });
这个全栈解决方案包含:
-
前端:响应式聊天界面
-
后端:RESTful API服务
-
模拟AI对话逻辑
-
完整的请求处理流程
-
错误处理机制
-
样式美观的UI界面
你可以通过修改getAIReply函数来实现更复杂的逻辑,或集成真实的AI API(如OpenAI、文心一言等)。