使用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> <title>Taotoken对话演示</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> <h1>Taotoken多轮对话演示</h1> <div id="chat"></div> <input type="text" id="input" placeholder="输入消息..."> <button onclick="sendMessage()">发送</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> </html>4. 启动与测试应用
在项目根目录下执行:
node server.js打开浏览器访问http://localhost:3000/public/index.html即可开始对话。每次交互都会保留上下文,实现真正的多轮对话。
5. 查看用量数据
在Taotoken控制台可以查看应用的API使用情况:
- 进入「用量分析」页面
- 选择时间范围查看请求次数和Token消耗
- 可筛选特定API Key查看该应用的独立用量
6. 部署建议
要将此演示部署到生产环境,建议:
- 将API Key存储在环境变量中
- 添加用户认证机制
- 实现对话历史持久化存储
- 设置合理的速率限制
Taotoken平台提供了完整的API文档和更多模型选择,可根据需要扩展此应用的功能。