使用 Node.js 在 Ubuntu 服务端接入 Taotoken 实现异步聊天补全
1. 环境准备
在 Ubuntu 服务器上运行 Node.js 服务需要确保已安装合适版本的运行环境。建议使用 Node.js 18.x 或更高 LTS 版本以获得最佳兼容性。可通过以下命令安装 Node.js 和 npm:
curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash - sudo apt-get install -y nodejs验证安装是否成功:
node -v npm -v接下来创建项目目录并初始化 npm 项目:
mkdir taotoken-nodejs && cd taotoken-nodejs npm init -y2. 安装依赖与配置
安装 OpenAI 官方 JavaScript 客户端库,这是与 Taotoken 兼容的 SDK:
npm install openai在项目根目录创建.env文件用于存储环境变量:
touch .env将 Taotoken API Key 添加到.env文件中。Key 可在 Taotoken 控制台的「API 密钥」页面获取:
TAOTOKEN_API_KEY=your_api_key_here安全提示:确保.env文件不被提交到版本控制系统。可将.env添加到.gitignore文件中。
3. 编写异步聊天补全代码
创建index.js文件作为服务入口点。以下示例展示了如何异步调用 Taotoken 的聊天补全接口:
import 'dotenv/config' import OpenAI from 'openai' const client = new OpenAI({ apiKey: process.env.TAOTOKEN_API_KEY, baseURL: 'https://taotoken.net/api', }) async function getChatCompletion(messages, model = 'claude-sonnet-4-6') { try { const completion = await client.chat.completions.create({ model, messages, temperature: 0.7, }) return completion.choices[0]?.message?.content } catch (error) { console.error('Error calling Taotoken API:', error) throw error } } // 示例使用 const exampleMessages = [ { role: 'system', content: '你是一个有帮助的助手' }, { role: 'user', content: 'Node.js 中如何读取环境变量?' }, ] getChatCompletion(exampleMessages) .then(response => console.log('Assistant:', response)) .catch(error => console.error('Error:', error))4. 运行与测试
安装dotenv包以加载环境变量:
npm install dotenv运行服务:
node index.js如果一切配置正确,您将看到来自 Taotoken 的响应输出到控制台。对于生产环境,建议使用 PM2 等进程管理器来保持服务运行:
npm install -g pm2 pm2 start index.js --name taotoken-service5. 进阶配置与优化
对于生产环境,您可能需要考虑以下优化措施:
- 请求超时设置:为 API 调用添加合理的超时时间
- 重试机制:实现指数退避重试策略处理临时性错误
- 日志记录:集成 Winston 或类似库记录请求和响应
- 速率限制:根据业务需求控制请求频率
以下是添加了基本错误处理和超时的改进版本:
import 'dotenv/config' import OpenAI from 'openai' import { setTimeout } from 'node:timers/promises' const client = new OpenAI({ apiKey: process.env.TAOTOKEN_API_KEY, baseURL: 'https://taotoken.net/api', timeout: 10000, // 10秒超时 }) async function getChatCompletionWithRetry(messages, model = 'claude-sonnet-4-6', maxRetries = 3) { let retryCount = 0 let lastError = null while (retryCount < maxRetries) { try { const completion = await client.chat.completions.create({ model, messages, temperature: 0.7, }) return completion.choices[0]?.message?.content } catch (error) { lastError = error retryCount++ if (retryCount < maxRetries) { const delay = Math.pow(2, retryCount) * 1000 await setTimeout(delay) } } } throw lastError }6. 部署注意事项
当将服务部署到生产环境时,请确保:
- 使用 HTTPS 保护所有 API 通信
- 实施适当的身份验证机制保护您的端点
- 监控 API 使用情况和性能
- 定期检查 Taotoken 控制台的用量统计
Taotoken 提供了详细的用量统计和 API 管理功能,可帮助您更好地监控和控制资源使用。