EcomGPT-中英文-7B电商模型Web开发全栈实践:从数据库设计到AI功能前端展示
EcomGPT-中英文-7B电商模型Web开发全栈实践从数据库设计到AI功能前端展示最近在做一个电商相关的智能小项目想把大模型的能力直接集成到网站里让用户能体验到AI优化商品描述和智能客服。选来选去发现EcomGPT-7B这个专门针对电商场景训练的中英文模型挺合适。它懂商品也懂营销话术生成的内容比较接地气。今天这篇文章我就带你从头到尾走一遍怎么用这个模型结合Python后端和Vue.js前端搭一个具备基础AI功能的简易电商网站。整个过程会涉及到数据库怎么设计、后端API怎么把模型接进来、前端页面怎么调用和展示。即使你之前没怎么接触过全栈或者大模型部署跟着步骤走也能把项目跑起来。1. 项目整体规划与环境准备在动手写代码之前我们先看看这个项目最终要长什么样以及需要准备哪些东西。1.1 我们要做一个什么样的网站这个网站不会像淘宝、京东那么复杂核心是展示“AI如何赋能电商”。它主要包含三个功能模块商品展示页一个简单的列表展示一些商品图片、名称、价格和描述。AI商品描述优化用户可以在商品详情页输入自己对商品的简单描述或需求比如“一款适合夏天穿的透气运动鞋”点击按钮让AI生成一段更吸引人、更专业的商品文案。智能客服聊天窗在网站角落有一个悬浮的聊天按钮点开后用户可以询问关于商品、订单、物流的常见问题由AI客服进行回答。技术栈上后端我选择用Python的Flask框架因为它轻量、灵活适合快速构建API。数据库用最常见的MySQL。前端用Vue.js 3配合Element Plus组件库能让我们快速搭建出好看的界面。最后把训练好的EcomGPT-7B模型加载到后端通过API提供文本生成服务。1.2 搭建你的开发环境工欲善其事必先利其器。先把下面这些软件和工具装好。后端环境Python 3.8这是必须的。建议使用Anaconda或Miniconda来管理Python环境避免包冲突。MySQL去官网下载安装并记住你设置的root密码。代码编辑器VS Code或PyCharm都可以看个人习惯。前端环境Node.jsVue.js的运行依赖。建议安装LTS长期支持版本。Vue CLI 或 Vite用于快速创建Vue项目。本文会用更现代的Vite。创建项目文件夹并初始化环境打开你的终端或命令行执行以下命令# 1. 创建一个项目总目录 mkdir smart-ecommerce-demo cd smart-ecommerce-demo # 2. 创建后端文件夹并进入 mkdir backend cd backend # 3. 创建Python虚拟环境以conda为例 conda create -n ecomgpt-env python3.10 conda activate ecomgpt-env # 4. 安装后端核心依赖 pip install flask flask-cors pymysql transformers torch # 5. 回到项目根目录创建前端文件夹 cd .. mkdir frontend cd frontend # 6. 使用Vite快速创建一个Vue项目 npm create vuelatest . # 在创建过程中你可以选择添加TypeScript、Router、Pinia等本文为简化可以先不选。 # 创建完成后安装Element Plus和Axios用于HTTP请求 npm install element-plus axios环境准备好后我们的项目结构雏形就有了。2. 数据库设计与后端API开发网站的数据得有个地方存后端的逻辑负责处理业务和调用AI模型。2.1 设计简单的数据库表我们不需要复杂的电商系统两张核心表就够了products商品表和chat_messages客服聊天记录表。先用MySQL命令行或图形化工具如Navicat创建一个数据库比如叫ecom_ai_db。然后执行下面的SQL语句来创建表-- 创建商品表 CREATE TABLE products ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255) NOT NULL COMMENT 商品名称, price DECIMAL(10, 2) NOT NULL COMMENT 商品价格, image_url VARCHAR(500) COMMENT 商品图片链接, description TEXT COMMENT 商品原始描述, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ) ENGINEInnoDB DEFAULT CHARSETutf8mb4 COMMENT商品表; -- 创建聊天消息表 CREATE TABLE chat_messages ( id INT AUTO_INCREMENT PRIMARY KEY, session_id VARCHAR(100) NOT NULL COMMENT 会话ID区分不同用户或会话, message TEXT NOT NULL COMMENT 消息内容, is_from_user BOOLEAN NOT NULL COMMENT 是否为用户发送的消息, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, INDEX idx_session (session_id) ) ENGINEInnoDB DEFAULT CHARSETutf8mb4 COMMENT智能客服聊天记录表; -- 插入一些示例商品数据 INSERT INTO products (name, price, image_url, description) VALUES (无线蓝牙降噪耳机, 699.00, https://example.com/images/headphone.jpg, 主动降噪续航30小时高保真音质), (便携式咖啡随行杯, 189.00, https://example.com/images/cup.jpg, 不锈钢材质保温保冷防漏设计), (智能运动手环, 299.00, https://example.com/images/band.jpg, 心率监测睡眠分析多种运动模式);2.2 构建Flask后端与基础API回到我们的backend文件夹开始编写后端代码。首先创建一个app.py作为主入口文件。# backend/app.py from flask import Flask, request, jsonify from flask_cors import CORS import pymysql import json from model_handler import generate_product_desc, generate_chat_response # 稍后我们会创建这个模型处理模块 app Flask(__name__) # 允许前端跨域请求开发时很重要 CORS(app) # 数据库配置请替换为你自己的配置 db_config { host: localhost, user: root, password: your_password, # 你的MySQL密码 database: ecom_ai_db, charset: utf8mb4 } def get_db_connection(): 获取数据库连接 return pymysql.connect(**db_config) # API 1: 获取商品列表 app.route(/api/products, methods[GET]) def get_products(): conn get_db_connection() cursor conn.cursor(pymysql.cursors.DictCursor) try: cursor.execute(SELECT id, name, price, image_url, description FROM products ORDER BY created_at DESC) products cursor.fetchall() return jsonify({code: 200, data: products}) except Exception as e: return jsonify({code: 500, msg: str(e)}) finally: cursor.close() conn.close() # API 2: AI优化商品描述 app.route(/api/optimize-description, methods[POST]) def optimize_description(): data request.json product_id data.get(product_id) user_input data.get(user_input) # 用户输入的简单描述或需求 if not product_id or not user_input: return jsonify({code: 400, msg: 缺少参数}) # 这里我们先模拟下一节会接入真实模型 # optimized_text generate_product_desc(user_input) optimized_text f[模拟AI生成] 这是一段根据您的需求‘{user_input}’生成的精美商品描述。实际会调用EcomGPT-7B模型。 return jsonify({code: 200, data: {optimized_description: optimized_text}}) # API 3: 处理智能客服聊天 app.route(/api/chat, methods[POST]) def handle_chat(): data request.json session_id data.get(session_id, default_session) user_message data.get(message) if not user_message: return jsonify({code: 400, msg: 消息内容不能为空}) # 1. 将用户消息存入数据库 conn get_db_connection() cursor conn.cursor() try: cursor.execute( INSERT INTO chat_messages (session_id, message, is_from_user) VALUES (%s, %s, %s), (session_id, user_message, True) ) conn.commit() except Exception as e: print(f保存用户消息失败: {e}) finally: cursor.close() conn.close() # 2. 调用AI模型生成回复模拟 # ai_response generate_chat_response(user_message) ai_response f[模拟AI客服] 您好关于‘{user_message}’我们的商品支持7天无理由退换货具体物流信息请查看订单详情。实际会调用EcomGPT-7B模型。 # 3. 将AI回复存入数据库 conn get_db_connection() cursor conn.cursor() try: cursor.execute( INSERT INTO chat_messages (session_id, message, is_from_user) VALUES (%s, %s, %s), (session_id, ai_response, False) ) conn.commit() except Exception as e: print(f保存AI回复失败: {e}) finally: cursor.close() conn.close() return jsonify({code: 200, data: {reply: ai_response}}) if __name__ __main__: app.run(debugTrue, port5000)现在你可以运行python app.py启动后端服务它会在http://localhost:5000监听请求。基础的API框架就搭好了。2.3 集成EcomGPT-7B模型这是最核心的一步。我们需要加载模型并编写处理函数。在backend目录下创建一个model_handler.py文件。# backend/model_handler.py from transformers import AutoTokenizer, AutoModelForCausalLM import torch # 全局变量避免重复加载 _model None _tokenizer None _device torch.device(cuda if torch.cuda.is_available() else cpu) def load_model(): 加载EcomGPT-7B模型和分词器 global _model, _tokenizer if _model is not None: return _model, _tokenizer model_name ECNU-IES/ECNU-IES/EcomGPT-7B # 假设的模型路径请替换为实际Hugging Face模型ID或本地路径 print(f正在加载模型 {model_name} 到 {_device}...) try: # 加载分词器 _tokenizer AutoTokenizer.from_pretrained(model_name, trust_remote_codeTrue) # 加载模型 _model AutoModelForCausalLM.from_pretrained( model_name, torch_dtypetorch.float16 if _device.type cuda else torch.float32, low_cpu_mem_usageTrue, trust_remote_codeTrue ).to(_device) _model.eval() # 设置为评估模式 print(模型加载完成) except Exception as e: print(f模型加载失败: {e}) # 为了演示我们在这里不退出而是使用模拟模式 _model None _tokenizer None return _model, _tokenizer def generate_product_desc(user_input): 根据用户输入生成商品描述 model, tokenizer load_model() if model is None: return f[模拟] 基于‘{user_input}’为您生成一段吸引人的电商文案。 # 构建适合EcomGPT的提示词。你需要根据模型的实际训练格式调整。 # 例如它可能训练时使用了特定的指令模板。 prompt f你是一个电商文案专家。请根据以下要求撰写一段吸引人的商品描述\n{user_input}\n\n描述 inputs tokenizer(prompt, return_tensorspt).to(_device) with torch.no_grad(): outputs model.generate( **inputs, max_new_tokens200, # 生成的最大长度 temperature0.8, # 控制随机性 do_sampleTrue, top_p0.95, # 核采样 ) generated_text tokenizer.decode(outputs[0], skip_special_tokensTrue) # 从生成的完整文本中提取我们需要的描述部分可能需要后处理 # 这里简单处理直接返回生成文本 return generated_text[len(prompt):] if generated_text.startswith(prompt) else generated_text def generate_chat_response(user_message): 生成智能客服回复 model, tokenizer load_model() if model is None: return f[模拟客服] 已收到您的问题‘{user_message}’正在为您查询。 # 构建客服对话提示词 prompt f你是一个专业的电商客服友好且乐于助人。用户说{user_message}\n客服回答 inputs tokenizer(prompt, return_tensorspt).to(_device) with torch.no_grad(): outputs model.generate( **inputs, max_new_tokens150, temperature0.7, do_sampleTrue, top_p0.9, ) generated_text tokenizer.decode(outputs[0], skip_special_tokensTrue) # 提取客服回答部分 reply generated_text[len(prompt):].split(\n)[0].strip() # 简单取第一行 return reply if reply else 抱歉我暂时无法理解您的问题请尝试换一种方式提问。重要提示在实际项目中EcomGPT-7B模型文件较大约14GB你需要确保有足够的GPU内存如16GB以上来加载。如果资源有限可以考虑使用量化版本如4bit量化或在CPU上运行速度会慢很多。将上面代码中的model_name替换为模型在Hugging Face上的实际ID或你下载到本地的路径。现在回到app.py取消注释掉调用generate_product_desc和generate_chat_response的代码替换掉模拟回复。这样后端就真正接入了AI模型。3. 前端Vue.js开发与界面实现后端准备好了我们来打造用户能看到和交互的界面。3.1 项目初始化与页面结构进入frontend目录修改src/App.vue文件搭建主要的页面框架。!-- frontend/src/App.vue -- template div idapp el-container !-- 顶部导航栏 -- el-header styletext-align: center; line-height: 60px; background-color: #409EFF; color: white; h1智能电商演示平台/h1 p体验AI优化商品描述与智能客服/p /el-header el-main !-- 商品列表区域 -- section h2精选商品/h2 product-list / /section !-- 其他说明或功能区 -- el-divider / section styletext-align: center; padding: 20px; h3功能说明/h3 p点击任意商品卡片进入详情页可使用AI优化描述功能。/p p页面右下角有智能客服浮窗随时为您解答疑问。/p /section /el-main el-footer styletext-align: center; padding: 20px; color: #666; p© 2023 智能电商演示项目 | 全栈开发实践/p /el-footer /el-container !-- 全局智能客服浮窗 -- chat-window / /div /template script setup import ProductList from ./components/ProductList.vue import ChatWindow from ./components/ChatWindow.vue /script style #app { font-family: Avenir, Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; color: #2c3e50; } /style3.2 商品列表与AI优化组件创建商品列表组件src/components/ProductList.vue它会展示商品并点击后进入详情页。!-- frontend/src/components/ProductList.vue -- template div classproduct-list el-row :gutter20 el-col :span8 v-forproduct in products :keyproduct.id stylemargin-bottom: 20px; el-card :body-style{ padding: 0px } shadowhover img :srcproduct.image_url || https://via.placeholder.com/300x200 classproduct-image / div stylepadding: 14px; h3{{ product.name }}/h3 p classprice¥{{ product.price }}/p p classdescription{{ product.description }}/p div classcard-footer el-button typeprimary clickgoToDetail(product.id) sizesmall查看详情/el-button /div /div /el-card /el-col /el-row !-- 商品详情弹窗 -- el-dialog v-modeldetailVisible :titlecurrentProduct?.name width50% div v-ifcurrentProduct el-image :srccurrentProduct.image_url fitcontain stylewidth: 100%; max-height: 300px;/el-image pstrong价格/strong¥{{ currentProduct.price }}/p pstrong原始描述/strong{{ currentProduct.description }}/p el-divider / h4AI描述优化/h4 el-input v-modeluserInputForAI typetextarea :rows3 placeholder请输入您对商品的描述需求或想法例如突出卖点、面向年轻女性、强调性价比 / el-button typesuccess clickoptimizeDescription :loadingoptimizing stylemargin-top: 10px; 让AI优化描述 /el-button div v-ifoptimizedText stylemargin-top: 20px; padding: 15px; background-color: #f8f9fa; border-radius: 4px; h5AI优化后的描述/h5 p stylewhite-space: pre-wrap;{{ optimizedText }}/p el-button typetext clickcopyText(optimizedText)复制文案/el-button /div /div /el-dialog /div /template script setup import { ref, onMounted } from vue import { ElMessage } from element-plus import axios from axios const products ref([]) const detailVisible ref(false) const currentProduct ref(null) const userInputForAI ref() const optimizedText ref() const optimizing ref(false) // 获取商品列表 const fetchProducts async () { try { const response await axios.get(http://localhost:5000/api/products) if (response.data.code 200) { products.value response.data.data } else { ElMessage.error(获取商品列表失败) } } catch (error) { ElMessage.error(网络请求失败) console.error(error) } } // 查看商品详情 const goToDetail (productId) { currentProduct.value products.value.find(p p.id productId) detailVisible.value true // 重置优化相关状态 userInputForAI.value optimizedText.value } // 调用AI优化描述API const optimizeDescription async () { if (!userInputForAI.value.trim()) { ElMessage.warning(请输入优化需求) return } optimizing.value true try { const response await axios.post(http://localhost:5000/api/optimize-description, { product_id: currentProduct.value.id, user_input: userInputForAI.value }) if (response.data.code 200) { optimizedText.value response.data.data.optimized_description ElMessage.success(描述生成成功) } else { ElMessage.error(生成失败 response.data.msg) } } catch (error) { ElMessage.error(请求出错) console.error(error) } finally { optimizing.value false } } // 复制文本到剪贴板 const copyText (text) { navigator.clipboard.writeText(text).then(() { ElMessage.success(文案已复制) }) } onMounted(() { fetchProducts() }) /script style scoped .product-image { width: 100%; height: 200px; object-fit: cover; display: block; } .price { color: #f56c6c; font-size: 18px; font-weight: bold; } .description { color: #666; font-size: 14px; height: 40px; overflow: hidden; text-overflow: ellipsis; } .card-footer { display: flex; justify-content: space-between; align-items: center; margin-top: 10px; } /style3.3 智能客服聊天组件创建客服聊天组件src/components/ChatWindow.vue实现一个可拖拽、可收起的悬浮聊天窗。!-- frontend/src/components/ChatWindow.vue -- template div classchat-wrapper :style{ bottom: position.y px, right: position.x px } v-ifvisible div classchat-header mousedownstartDrag span智能客服/span el-button link clicktoggleVisible el-iconClose //el-icon /el-button /div div classchat-body div classmessages refmessagesRef div v-for(msg, index) in messages :keyindex :class[message, msg.isFromUser ? user : ai] div classavatar{{ msg.isFromUser ? 你 : AI }}/div div classbubble{{ msg.text }}/div /div /div div classinput-area el-input v-modelinputMessage placeholder输入您的问题... keyup.entersendMessage :disabledsending template #append el-button clicksendMessage :loadingsending el-iconPromotion //el-icon /el-button /template /el-input /div /div /div !-- 悬浮按钮 -- div classchat-button clicktoggleVisible v-if!visible el-icon size24ChatDotRound //el-icon /div /template script setup import { ref, onMounted, nextTick } from vue import { ElMessage } from element-plus import { Close, Promotion, ChatDotRound } from element-plus/icons-vue import axios from axios const visible ref(false) const inputMessage ref() const messages ref([]) const sending ref(false) const messagesRef ref(null) const position ref({ x: 20, y: 20 }) const isDragging ref(false) const dragOffset ref({ x: 0, y: 0 }) // 初始化欢迎语 onMounted(() { messages.value.push({ text: 您好我是智能客服可以为您解答商品、订单、物流等问题。, isFromUser: false, timestamp: new Date() }) }) // 发送消息 const sendMessage async () { const text inputMessage.value.trim() if (!text) return // 添加用户消息到界面 messages.value.push({ text, isFromUser: true, timestamp: new Date() }) inputMessage.value scrollToBottom() sending.value true try { const response await axios.post(http://localhost:5000/api/chat, { session_id: web_demo_session, // 可以用更复杂的逻辑生成唯一会话ID message: text }) if (response.data.code 200) { // 添加AI回复到界面 messages.value.push({ text: response.data.data.reply, isFromUser: false, timestamp: new Date() }) scrollToBottom() } else { ElMessage.error(客服回复失败 response.data.msg) } } catch (error) { ElMessage.error(网络请求失败) console.error(error) } finally { sending.value false } } // 滚动到消息底部 const scrollToBottom () { nextTick(() { if (messagesRef.value) { messagesRef.value.scrollTop messagesRef.value.scrollHeight } }) } // 切换聊天窗口显示/隐藏 const toggleVisible () { visible.value !visible.value if (visible.value) { scrollToBottom() } } // 拖拽相关逻辑 const startDrag (e) { isDragging.value true dragOffset.value.x e.clientX - position.value.x dragOffset.value.y e.clientY - position.value.y document.addEventListener(mousemove, onDrag) document.addEventListener(mouseup, stopDrag) } const onDrag (e) { if (!isDragging.value) return position.value.x Math.max(0, Math.min(window.innerWidth - 350, e.clientX - dragOffset.value.x)) position.value.y Math.max(0, Math.min(window.innerHeight - 500, e.clientY - dragOffset.value.y)) } const stopDrag () { isDragging.value false document.removeEventListener(mousemove, onDrag) document.removeEventListener(mouseup, stopDrag) } /script style scoped .chat-wrapper { position: fixed; width: 320px; height: 450px; background: white; border-radius: 10px; box-shadow: 0 5px 20px rgba(0, 0, 0, 0.2); display: flex; flex-direction: column; z-index: 9999; overflow: hidden; } .chat-header { background: #409EFF; color: white; padding: 12px 15px; display: flex; justify-content: space-between; align-items: center; cursor: move; user-select: none; } .chat-body { flex: 1; display: flex; flex-direction: column; } .messages { flex: 1; padding: 15px; overflow-y: auto; background: #f9f9f9; } .message { display: flex; margin-bottom: 15px; } .message.user { flex-direction: row-reverse; } .avatar { width: 32px; height: 32px; border-radius: 50%; background: #409EFF; color: white; display: flex; align-items: center; justify-content: center; font-size: 12px; flex-shrink: 0; margin: 0 8px; } .message.user .avatar { background: #67c23a; } .bubble { max-width: 70%; padding: 10px 15px; border-radius: 18px; background: white; box-shadow: 0 2px 5px rgba(0,0,0,0.1); word-break: break-word; } .message.user .bubble { background: #95d475; color: white; } .input-area { padding: 15px; border-top: 1px solid #eee; } .chat-button { position: fixed; bottom: 30px; right: 30px; width: 60px; height: 60px; background: #409EFF; color: white; border-radius: 50%; display: flex; align-items: center; justify-content: center; box-shadow: 0 4px 12px rgba(64, 158, 255, 0.5); cursor: pointer; z-index: 9998; transition: transform 0.3s; } .chat-button:hover { transform: scale(1.1); } /style3.4 配置与运行前端最后我们需要配置一下前端项目的请求代理避免跨域问题。在frontend目录下创建或修改vite.config.js文件。// frontend/vite.config.js import { defineConfig } from vite import vue from vitejs/plugin-vue export default defineConfig({ plugins: [vue()], server: { proxy: { /api: { target: http://localhost:5000, // 你的Flask后端地址 changeOrigin: true, rewrite: (path) path.replace(/^\/api/, ) // 如果你的后端API没有/api前缀可以去掉这行 } } } })现在在frontend目录下运行npm run dev你的前端开发服务器就启动了通常是http://localhost:5173。同时确保你的Flask后端也在运行。打开浏览器访问前端地址你应该能看到一个完整的、具备商品展示、AI描述优化和智能客服聊天功能的简易电商网站了。4. 项目总结与后续思考走完这一整套流程一个集成AI能力的简易电商网站就从无到有搭建起来了。从设计数据库表到用Flask编写API并接入EcomGPT-7B模型再到用Vue.js构建出交互友好的前端界面每一步都是全栈开发中非常典型的实践。实际做下来我感觉最大的挑战和乐趣都在模型集成那一步。把一个大模型塞进Web应用里让它能稳定、快速地响应用户请求需要考虑模型加载、推理速度、并发处理等一系列工程问题。我们这个demo为了简洁用了比较简单的加载方式。在生产环境中你可能需要考虑使用模型服务化框架如TGI, vLLM或者通过API调用云端的大模型服务来获得更好的性能和稳定性。前端部分利用Vue 3的响应式和Element Plus的组件能非常快地搭建出可用的界面。那个可拖拽的客服窗口虽然是个小功能但能极大提升用户体验。这个项目完全可以作为一个起点继续扩展更多功能比如用户登录、购物车、真实的订单流程或者集成更复杂的AI功能如图像生成商品主图、基于用户评论的情感分析等等。希望这个全栈实践能给你带来一些启发动手试试把想法变成现实。获取更多AI镜像想探索更多AI镜像和应用场景访问 CSDN星图镜像广场提供丰富的预置镜像覆盖大模型推理、图像生成、视频生成、模型微调等多个领域支持一键部署。
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2555303.html
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!