使用Node.js和Taotoken构建一个简单的多轮对话演示应用
使用Node.js和Taotoken构建一个简单的多轮对话演示应用1. 环境准备与项目初始化首先确保已安装Node.js 18或更高版本。创建一个新目录并初始化项目mkdir taotoken-chat-demo cd taotoken-chat-demo npm init -y npm install express openai body-parser cors在Taotoken控制台获取API Key登录https://taotoken.net并进入控制台在「API密钥」页面创建新密钥复制生成的密钥字符串备用2. 服务端API封装创建server.js文件实现核心逻辑const express require(express); const { OpenAI } require(openai); const bodyParser require(body-parser); const cors require(cors); const app express(); app.use(bodyParser.json()); app.use(cors()); const client new OpenAI({ apiKey: process.env.TAOTOKEN_API_KEY || YOUR_API_KEY, baseURL: https://taotoken.net/api, }); const conversationHistory {}; app.post(/chat, async (req, res) { const { userId, message } req.body; if (!conversationHistory[userId]) { conversationHistory[userId] []; } conversationHistory[userId].push({ role: user, content: message }); try { const completion await client.chat.completions.create({ model: claude-sonnet-4-6, messages: conversationHistory[userId], }); const reply completion.choices[0]?.message?.content; conversationHistory[userId].push({ role: assistant, content: reply }); res.json({ reply }); } catch (error) { console.error(API Error:, error); res.status(500).json({ error: 对话处理失败 }); } }); const PORT process.env.PORT || 3000; app.listen(PORT, () { console.log(Server running on port ${PORT}); });3. 前端界面实现创建public/index.html文件!DOCTYPE html html head titleTaotoken对话演示/title style body { font-family: Arial, sans-serif; max-width: 800px; margin: 0 auto; padding: 20px; } #chat { border: 1px solid #ddd; height: 400px; overflow-y: scroll; padding: 10px; margin-bottom: 10px; } #input { width: 70%; padding: 8px; } button { padding: 8px 15px; } /style /head body h1Taotoken多轮对话演示/h1 div idchat/div input typetext idinput placeholder输入消息... button onclicksendMessage()发送/button script const userId user_ Math.random().toString(36).substr(2, 9); const chatDiv document.getElementById(chat); function appendMessage(role, content) { const msgDiv document.createElement(div); msgDiv.innerHTML strong${role}:/strong ${content}; chatDiv.appendChild(msgDiv); chatDiv.scrollTop chatDiv.scrollHeight; } async function sendMessage() { const input document.getElementById(input); const message input.value.trim(); if (!message) return; appendMessage(你, message); input.value ; try { const response await fetch(http://localhost:3000/chat, { method: POST, headers: { Content-Type: application/json }, body: JSON.stringify({ userId, message }), }); const data await response.json(); if (data.reply) { appendMessage(AI, data.reply); } } catch (error) { console.error(Error:, error); appendMessage(系统, 对话请求失败); } } /script /body /html4. 启动与测试应用在项目根目录下执行node server.js打开浏览器访问http://localhost:3000/public/index.html即可开始对话。每次交互都会保留上下文实现真正的多轮对话。5. 查看用量数据在Taotoken控制台可以查看应用的API使用情况进入「用量分析」页面选择时间范围查看请求次数和Token消耗可筛选特定API Key查看该应用的独立用量6. 部署建议要将此演示部署到生产环境建议将API Key存储在环境变量中添加用户认证机制实现对话历史持久化存储设置合理的速率限制Taotoken平台提供了完整的API文档和更多模型选择可根据需要扩展此应用的功能。