
本文将介绍如何使用 Node.js 调用 DeepSeek API,实现流式对话并保存对话记录。Node.js 版本使用现代异步编程方式实现,支持流式处理和错误处理。
deepseek-project/ ├── main.js # 主程序 ├── package.json # 项目配置文件 └── conversation.txt # 对话记录文件
在项目目录下打开命令行,执行:
# 安装项目依赖 npm install # 如果出现权限问题,可以尝试: sudo npm install # Linux/Mac # 或 npm install --force # Windows
此命令会安装 package.json 中定义的所有依赖项:
如果安装过程中遇到网络问题,可以尝试使用国内镜像:
# 设置淘宝镜像 npm config set registry https://registry.npmmirror.com # 然后重新安装 npm install
安装完依赖后,使用以下命令启动程序:
# 使用 npm 启动 npm start # 或者直接使用 node node main.js
如果遇到权限问题:
# Linux/Mac sudo npm start # Windows (以管理员身份运行命令提示符) npm start
{ "name": "deepseek-chat", "version": "1.0.0", "description": "DeepSeek API chat implementation in Node.js", "main": "main.js", "scripts": { "start": "node main.js" }, "dependencies": { "axios": "^1.6.2", "moment": "^2.29.4" } }
const fs = require('fs').promises; const readline = require('readline'); const axios = require('axios'); const moment = require('moment'); class DeepSeekChat { constructor() { this.url = 'https://api.siliconflow.cn/v1/chat/completions'; this.apiKey = 'YOUR_API_KEY'; // 替换为你的 API Key this.logFile = 'conversation.txt'; } async saveToFile(content, isQuestion = false) { const timestamp = moment().format('YYYY-MM-DD HH:mm:ss'); const text = isQuestion ? `\n[${timestamp}] Question:\n${content}\n\n[${timestamp}] Answer:\n` : content; await fs.appendFile(this.logFile, text); } async chat() { // 创建命令行接口 const rl = readline.createInterface({ input: process.stdin, output: process.stdout }); // 使用 Promise 封装问题输入 const question = (prompt) => new Promise((resolve) => rl.question(prompt, resolve)); try { while (true) { const userInput = await question('\n请输入您的问题 (输入 q 退出): '); if (userInput.trim().toLowerCase() === 'q') { console.log('程序已退出'); break; } // 保存问题 await this.saveToFile(userInput, true); // 准备请求数据 const data = { model: 'deepseek-ai/DeepSeek-V3', messages: [ { role: 'user', content: userInput } ], stream: true, max_tokens: 2048, temperature: 0.7, top_p: 0.7, top_k: 50, frequency_penalty: 0.5, n: 1, response_format: { type: 'text' } }; try { // 发送流式请求 const response = await axios({ method: 'post', url: this.url, data: data, headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${this.apiKey}` }, responseType: 'stream' }); // 处理流式响应 response.data.on('data', async (chunk) => { const lines = chunk.toString().split('\n'); for (const line of lines) { if (line.trim() === '') continue; if (line.trim() === 'data: [DONE]') continue; if (line.startsWith('data: ')) { try { const json = JSON.parse(line.slice(6)); if (json.choices[0].delta.content) { const content = json.choices[0].delta.content; process.stdout.write(content); await this.saveToFile(content); } } catch (e) { continue; } } } }); // 等待响应完成 await new Promise((resolve) => { response.data.on('end', async () => { console.log('\n----------------------------------------'); await this.saveToFile('\n----------------------------------------\n'); resolve(); }); }); } catch (error) { const errorMsg = `请求错误: ${error.message}\n`; console.error(errorMsg); await this.saveToFile(errorMsg); } } } finally { rl.close(); } } } // 运行程序 async function main() { const chatbot = new DeepSeekChat(); await chatbot.chat(); } main().catch(console.error);
DeepSeekChat
: 主类,封装所有功能constructor
: 构造函数,初始化配置saveToFile
: 异步保存对话记录chat
: 主对话循环async saveToFile(content, isQuestion = false) { const timestamp = moment().format('YYYY-MM-DD HH:mm:ss'); const text = isQuestion ? `\n[${timestamp}] Question:\n${content}\n\n[${timestamp}] Answer:\n` : content; await fs.appendFile(this.logFile, text); }
response.data.on('data', async (chunk) => { const lines = chunk.toString().split('\n'); for (const line of lines) { if (line.startsWith('data: ')) { const json = JSON.parse(line.slice(6)); if (json.choices[0].delta.content) { const content = json.choices[0].delta.content; process.stdout.write(content); await this.saveToFile(content); } } } });
model
: 使用的模型名称stream
: 启用流式输出max_tokens
: 最大输出长度 (2048)temperature
: 控制随机性 (0.7)top_p
, top_k
: 采样参数frequency_penalty
: 重复惩罚系数代码包含完整的错误处理机制:
在项目目录下打开命令行,执行:
# 安装项目依赖 npm install # 如果出现权限问题,可以尝试: sudo npm install # Linux/Mac # 或 npm install --force # Windows
此命令会安装 package.json 中定义的所有依赖项:
如果安装过程中遇到网络问题,可以尝试使用国内镜像:
# 设置淘宝镜像 npm config set registry https://registry.npmmirror.com # 然后重新安装 npm install
在 main.js
中替换 YOUR_API_KEY
为你的实际 API Key。
安装完依赖后,使用以下命令启动程序:
# 使用 npm 启动 npm start # 或者直接使用 node node main.js
如果遇到权限问题:
# Linux/Mac sudo npm start # Windows (以管理员身份运行命令提示符) npm start
内存管理
错误处理
并发控制
Node.js 版本的 DeepSeek API 实现充分利用了异步编程特性,提供了流畅的对话体验和完善的错误处理机制。代码结构清晰,易于维护和扩展。
以上就是Node.js调用DeepSeek API完整指南的详细内容,更多关于Node.js调用DeepSeek API的资料请关注本站其它相关文章!