使用 Node.js 快速构建接入 Taotoken 的 AI 客服原型

1. 环境准备与初始化

在开始构建 AI 客服原型前,请确保已安装 Node.js 16 或更高版本。创建一个新项目目录并初始化 npm 包管理:

mkdir ai-customer-service && cd ai-customer-service
npm init -y
npm install openai express body-parser dotenv

创建 .env 文件用于存储敏感信息,内容如下:

TAOTOKEN_API_KEY=your_api_key_here
PORT=3000

2. 配置 Taotoken 连接

使用 OpenAI 官方 JavaScript SDK 连接 Taotoken 端点时,关键配置是正确设置 baseURLapiKey。创建 taotoken-client.js 文件:

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',
});

export default client;

3. 实现基础聊天接口

创建 server.js 文件实现 Express 服务,处理用户消息并返回 AI 响应:

import express from 'express';
import bodyParser from 'body-parser';
import client from './taotoken-client.js';

const app = express();
app.use(bodyParser.json());

app.post('/chat', async (req, res) => {
  try {
    const { messages, model = 'claude-sonnet-4-6' } = req.body;
    
    const completion = await client.chat.completions.create({
      model,
      messages,
      temperature: 0.7,
    });

    res.json({ reply: completion.choices[0].message.content });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

app.listen(process.env.PORT, () => {
  console.log(`Server running on port ${process.env.PORT}`);
});

4. 添加流式响应支持

对于需要实时显示响应的场景,可以修改接口支持流式传输:

app.post('/chat-stream', async (req, res) => {
  try {
    const { messages, model = 'claude-sonnet-4-6' } = req.body;
    
    res.setHeader('Content-Type', 'text/event-stream');
    res.setHeader('Cache-Control', 'no-cache');
    res.setHeader('Connection', 'keep-alive');

    const stream = await client.chat.completions.create({
      model,
      messages,
      temperature: 0.7,
      stream: true,
    });

    for await (const chunk of stream) {
      const content = chunk.choices[0]?.delta?.content || '';
      res.write(`data: ${JSON.stringify({ content })}\n\n`);
    }
    
    res.end();
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

5. 前端界面集成

创建简单的 HTML 界面与后端交互,在 public/index.html 中:

<!DOCTYPE html>
<html>
<head>
  <title>AI 客服演示</title>
  <script>
    async function sendMessage() {
      const input = document.getElementById('message');
      const output = document.getElementById('output');
      
      output.innerHTML += `<div>用户: ${input.value}</div>`;
      
      const response = await fetch('/chat', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          messages: [{ role: 'user', content: input.value }]
        })
      });
      
      const { reply } = await response.json();
      output.innerHTML += `<div>AI: ${reply}</div>`;
      input.value = '';
    }
  </script>
</head>
<body>
  <div id="output" style="height: 300px; overflow-y: scroll; border: 1px solid #ccc;"></div>
  <input id="message" type="text" placeholder="输入消息...">
  <button onclick="sendMessage()">发送</button>
</body>
</html>

6. 模型切换与扩展

Taotoken 支持通过修改 model 参数切换不同模型。可以在前端添加模型选择器:

<select id="model">
  <option value="claude-sonnet-4-6">Claude Sonnet</option>
  <option value="gpt-3.5-turbo">GPT-3.5 Turbo</option>
  <!-- 其他模型选项可在 Taotoken 模型广场查看 -->
</select>

然后修改 sendMessage 函数:

const model = document.getElementById('model').value;
const response = await fetch('/chat', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    messages: [{ role: 'user', content: input.value }],
    model
  })
});

现在您已经完成了一个支持多模型切换的 AI 客服原型。要开始使用 Taotoken,请访问 Taotoken 获取 API Key 并探索更多可用模型。

Logo

汇聚全球AI编程工具,助力开发者即刻编程。

更多推荐