告别海外账号与网络限制稳定直连全球优质大模型限时半价接入中。 点击领取海量免费额度使用 Node.js 构建服务并接入 Taotoken 多模型 API对于 Node.js 开发者而言将大模型能力集成到后端服务中已成为提升应用智能水平的关键步骤。直接对接多家模型厂商的 API 往往意味着需要管理多个密钥、处理不同的调用规范以及应对复杂的计费统计。Taotoken 平台通过提供统一的 OpenAI 兼容 API简化了这一过程。本文将指导你从零开始在 Node.js 服务中集成 Taotoken快速获得调用多种大模型的能力。1. 前期准备获取 API Key 与模型 ID在开始编写代码之前你需要在 Taotoken 平台完成两项基础配置。首先登录 Taotoken 控制台在 API 密钥管理页面创建一个新的密钥。请妥善保存生成的密钥字符串它将在后续步骤中作为身份凭证使用。建议在创建时根据业务需要设置适当的权限与额度。其次你需要确定要调用的模型。前往平台的模型广场浏览当前支持的各类模型。每个模型都有一个唯一的标识符例如claude-sonnet-4-6或gpt-4o-mini。记录下你计划使用的模型 ID它将在 API 请求中指定。为了安全地管理密钥我们强烈建议使用环境变量避免将敏感信息硬编码在代码中。2. 项目初始化与依赖安装创建一个新的 Node.js 项目目录并初始化项目。mkdir taotoken-node-service cd taotoken-node-service npm init -y接下来安装必要的依赖。核心是openai这个官方 SDK它完美兼容 Taotoken 的 API 接口。此外我们通常会使用dotenv来管理环境变量并使用express来构建一个简单的 Web 服务示例。npm install openai dotenv express安装完成后在项目根目录创建一个.env文件用于存储环境变量。TAOTOKEN_API_KEY你的_API_密钥 DEFAULT_MODELclaude-sonnet-4-6 PORT3000请务必将.env文件添加到.gitignore中以防止密钥被意外提交至代码仓库。3. 配置 OpenAI 客户端并发起请求现在我们来编写核心的 API 调用代码。创建一个名为service.js的文件。首先加载环境变量并初始化 OpenAI 客户端。关键在于正确设置baseURL参数将其指向 Taotoken 的 API 端点。import OpenAI from ‘openai‘; import dotenv from ‘dotenv‘; dotenv.config(); const client new OpenAI({ apiKey: process.env.TAOTOKEN_API_KEY, baseURL: ‘https://taotoken.net/api‘, });请注意baseURL的值是https://taotoken.net/api。OpenAI SDK 会自动在此基础路径上拼接/v1/chat/completions等具体的接口路径。这是与 Taotoken 平台对接的正确配置。接下来我们可以编写一个异步函数来调用聊天补全接口。async function getChatCompletion(messages, model process.env.DEFAULT_MODEL) { try { const completion await client.chat.completions.create({ model: model, messages: messages, // 可根据需要添加其他参数如 temperature、max_tokens 等 }); return completion.choices[0]?.message?.content; } catch (error) { console.error(‘API调用失败:‘, error); throw error; } } // 示例调用 const exampleMessages [ { role: ‘user‘, content: ‘请用一句话介绍你自己。‘ } ]; getChatCompletion(exampleMessages) .then(response console.log(‘模型回复:‘, response)) .catch(err console.error(‘出错:‘, err));这段代码定义了一个通用的函数接收消息列表和可选的模型参数返回模型生成的文本内容。错误处理被包裹在 try-catch 块中这对于生产环境至关重要。4. 处理流式响应对于需要实时输出或处理长文本的场景流式响应Streaming能显著提升用户体验。Taotoken 的 API 同样支持此功能。修改你的调用函数处理流式返回的数据。async function getStreamingChatCompletion(messages, model process.env.DEFAULT_MODEL, onChunk) { try { const stream await client.chat.completions.create({ model: model, messages: messages, stream: true, }); let fullContent ‘‘; for await (const chunk of stream) { const content chunk.choices[0]?.delta?.content || ‘‘; fullContent content; // 如果传入了回调函数则实时处理每个数据块 if (onChunk typeof onChunk ‘function‘) { onChunk(content); } } return fullContent; } catch (error) { console.error(‘流式API调用失败:‘, error); throw error; } } // 示例调用实时打印输出 getStreamingChatCompletion( [{ role: ‘user‘, content: ‘写一首关于春天的短诗。‘ }], process.env.DEFAULT_MODEL, (chunk) process.stdout.write(chunk) ).then(fullText console.log(‘\n\n流式接收完成。‘));通过将stream参数设为trueAPI 会返回一个可迭代的流对象。我们可以通过for await...of循环逐步获取并拼接回复内容同时也能实现前端 SSEServer-Sent Events或类似的实时推送机制。5. 构建一个简单的 REST API 服务最后我们将上述功能封装成一个简单的 HTTP 服务提供一个可外部调用的端点。创建server.js文件。import express from ‘express‘; import dotenv from ‘dotenv‘; import { getChatCompletion, getStreamingChatCompletion } from ‘./service.js‘; dotenv.config(); const app express(); app.use(express.json()); app.post(‘/api/chat‘, async (req, res) { const { messages, model, stream } req.body; const targetModel model || process.env.DEFAULT_MODEL; if (!messages || !Array.isArray(messages)) { return res.status(400).json({ error: ‘messages 字段必须是一个数组‘ }); } try { if (stream) { // 设置流式响应头 res.setHeader(‘Content-Type‘, ‘text/plain; charsetutf-8‘); res.setHeader(‘Transfer-Encoding‘, ‘chunked‘); await getStreamingChatCompletion(messages, targetModel, (chunk) { res.write(chunk); }); res.end(); } else { const content await getChatCompletion(messages, targetModel); res.json({ model: targetModel, response: content }); } } catch (error) { console.error(‘服务端处理错误:‘, error); res.status(500).json({ error: ‘内部服务器错误‘, details: error.message }); } }); const PORT process.env.PORT || 3000; app.listen(PORT, () { console.log(服务已启动监听端口 ${PORT}); console.log(测试端点: POST http://localhost:${PORT}/api/chat); });这个简单的 Express 服务暴露了一个/api/chat的 POST 接口。请求体需要包含messages并可选择指定model和是否启用stream。服务会根据参数决定返回普通的 JSON 响应还是流式文本。6. 运行与测试启动你的服务。node server.js你可以使用curl命令或 Postman 等工具进行测试。非流式调用测试curl -X POST http://localhost:3000/api/chat \ -H Content-Type: application/json \ -d ‘{ messages: [{role: user, content: 你好请简单打招呼。}], model: gpt-4o-mini }‘流式调用测试curl -X POST http://localhost:3000/api/chat \ -H Content-Type: application/json \ -d ‘{ messages: [{role: user, content: 简述太阳系。}], stream: true }‘至此你已经成功构建了一个可以接入 Taotoken 多模型 API 的 Node.js 后端服务。通过修改请求中的model参数你可以轻松切换使用平台支持的不同大模型而无需更改任何底层代码或密钥配置。所有调用都将通过统一的 Taotoken API Key 进行计费和用量统计方便你在控制台进行统一管理。开始你的多模型集成之旅可以访问 Taotoken 创建密钥并查看完整的模型列表与文档。 告别海外账号与网络限制稳定直连全球优质大模型限时半价接入中。 点击领取海量免费额度
使用 Node.js 构建服务并接入 Taotoken 多模型 API
告别海外账号与网络限制稳定直连全球优质大模型限时半价接入中。 点击领取海量免费额度使用 Node.js 构建服务并接入 Taotoken 多模型 API对于 Node.js 开发者而言将大模型能力集成到后端服务中已成为提升应用智能水平的关键步骤。直接对接多家模型厂商的 API 往往意味着需要管理多个密钥、处理不同的调用规范以及应对复杂的计费统计。Taotoken 平台通过提供统一的 OpenAI 兼容 API简化了这一过程。本文将指导你从零开始在 Node.js 服务中集成 Taotoken快速获得调用多种大模型的能力。1. 前期准备获取 API Key 与模型 ID在开始编写代码之前你需要在 Taotoken 平台完成两项基础配置。首先登录 Taotoken 控制台在 API 密钥管理页面创建一个新的密钥。请妥善保存生成的密钥字符串它将在后续步骤中作为身份凭证使用。建议在创建时根据业务需要设置适当的权限与额度。其次你需要确定要调用的模型。前往平台的模型广场浏览当前支持的各类模型。每个模型都有一个唯一的标识符例如claude-sonnet-4-6或gpt-4o-mini。记录下你计划使用的模型 ID它将在 API 请求中指定。为了安全地管理密钥我们强烈建议使用环境变量避免将敏感信息硬编码在代码中。2. 项目初始化与依赖安装创建一个新的 Node.js 项目目录并初始化项目。mkdir taotoken-node-service cd taotoken-node-service npm init -y接下来安装必要的依赖。核心是openai这个官方 SDK它完美兼容 Taotoken 的 API 接口。此外我们通常会使用dotenv来管理环境变量并使用express来构建一个简单的 Web 服务示例。npm install openai dotenv express安装完成后在项目根目录创建一个.env文件用于存储环境变量。TAOTOKEN_API_KEY你的_API_密钥 DEFAULT_MODELclaude-sonnet-4-6 PORT3000请务必将.env文件添加到.gitignore中以防止密钥被意外提交至代码仓库。3. 配置 OpenAI 客户端并发起请求现在我们来编写核心的 API 调用代码。创建一个名为service.js的文件。首先加载环境变量并初始化 OpenAI 客户端。关键在于正确设置baseURL参数将其指向 Taotoken 的 API 端点。import OpenAI from ‘openai‘; import dotenv from ‘dotenv‘; dotenv.config(); const client new OpenAI({ apiKey: process.env.TAOTOKEN_API_KEY, baseURL: ‘https://taotoken.net/api‘, });请注意baseURL的值是https://taotoken.net/api。OpenAI SDK 会自动在此基础路径上拼接/v1/chat/completions等具体的接口路径。这是与 Taotoken 平台对接的正确配置。接下来我们可以编写一个异步函数来调用聊天补全接口。async function getChatCompletion(messages, model process.env.DEFAULT_MODEL) { try { const completion await client.chat.completions.create({ model: model, messages: messages, // 可根据需要添加其他参数如 temperature、max_tokens 等 }); return completion.choices[0]?.message?.content; } catch (error) { console.error(‘API调用失败:‘, error); throw error; } } // 示例调用 const exampleMessages [ { role: ‘user‘, content: ‘请用一句话介绍你自己。‘ } ]; getChatCompletion(exampleMessages) .then(response console.log(‘模型回复:‘, response)) .catch(err console.error(‘出错:‘, err));这段代码定义了一个通用的函数接收消息列表和可选的模型参数返回模型生成的文本内容。错误处理被包裹在 try-catch 块中这对于生产环境至关重要。4. 处理流式响应对于需要实时输出或处理长文本的场景流式响应Streaming能显著提升用户体验。Taotoken 的 API 同样支持此功能。修改你的调用函数处理流式返回的数据。async function getStreamingChatCompletion(messages, model process.env.DEFAULT_MODEL, onChunk) { try { const stream await client.chat.completions.create({ model: model, messages: messages, stream: true, }); let fullContent ‘‘; for await (const chunk of stream) { const content chunk.choices[0]?.delta?.content || ‘‘; fullContent content; // 如果传入了回调函数则实时处理每个数据块 if (onChunk typeof onChunk ‘function‘) { onChunk(content); } } return fullContent; } catch (error) { console.error(‘流式API调用失败:‘, error); throw error; } } // 示例调用实时打印输出 getStreamingChatCompletion( [{ role: ‘user‘, content: ‘写一首关于春天的短诗。‘ }], process.env.DEFAULT_MODEL, (chunk) process.stdout.write(chunk) ).then(fullText console.log(‘\n\n流式接收完成。‘));通过将stream参数设为trueAPI 会返回一个可迭代的流对象。我们可以通过for await...of循环逐步获取并拼接回复内容同时也能实现前端 SSEServer-Sent Events或类似的实时推送机制。5. 构建一个简单的 REST API 服务最后我们将上述功能封装成一个简单的 HTTP 服务提供一个可外部调用的端点。创建server.js文件。import express from ‘express‘; import dotenv from ‘dotenv‘; import { getChatCompletion, getStreamingChatCompletion } from ‘./service.js‘; dotenv.config(); const app express(); app.use(express.json()); app.post(‘/api/chat‘, async (req, res) { const { messages, model, stream } req.body; const targetModel model || process.env.DEFAULT_MODEL; if (!messages || !Array.isArray(messages)) { return res.status(400).json({ error: ‘messages 字段必须是一个数组‘ }); } try { if (stream) { // 设置流式响应头 res.setHeader(‘Content-Type‘, ‘text/plain; charsetutf-8‘); res.setHeader(‘Transfer-Encoding‘, ‘chunked‘); await getStreamingChatCompletion(messages, targetModel, (chunk) { res.write(chunk); }); res.end(); } else { const content await getChatCompletion(messages, targetModel); res.json({ model: targetModel, response: content }); } } catch (error) { console.error(‘服务端处理错误:‘, error); res.status(500).json({ error: ‘内部服务器错误‘, details: error.message }); } }); const PORT process.env.PORT || 3000; app.listen(PORT, () { console.log(服务已启动监听端口 ${PORT}); console.log(测试端点: POST http://localhost:${PORT}/api/chat); });这个简单的 Express 服务暴露了一个/api/chat的 POST 接口。请求体需要包含messages并可选择指定model和是否启用stream。服务会根据参数决定返回普通的 JSON 响应还是流式文本。6. 运行与测试启动你的服务。node server.js你可以使用curl命令或 Postman 等工具进行测试。非流式调用测试curl -X POST http://localhost:3000/api/chat \ -H Content-Type: application/json \ -d ‘{ messages: [{role: user, content: 你好请简单打招呼。}], model: gpt-4o-mini }‘流式调用测试curl -X POST http://localhost:3000/api/chat \ -H Content-Type: application/json \ -d ‘{ messages: [{role: user, content: 简述太阳系。}], stream: true }‘至此你已经成功构建了一个可以接入 Taotoken 多模型 API 的 Node.js 后端服务。通过修改请求中的model参数你可以轻松切换使用平台支持的不同大模型而无需更改任何底层代码或密钥配置。所有调用都将通过统一的 Taotoken API Key 进行计费和用量统计方便你在控制台进行统一管理。开始你的多模型集成之旅可以访问 Taotoken 创建密钥并查看完整的模型列表与文档。 告别海外账号与网络限制稳定直连全球优质大模型限时半价接入中。 点击领取海量免费额度