简介
本文将介绍如何使用 node.js 调用 deepseek api,实现流式对话并保存对话记录。node.js 版本使用现代异步编程方式实现,支持流式处理和错误处理。
1. 环境准备
1.1 系统要求
- node.js 14.0 或更高版本
- npm 包管理器
1.2 项目结构
deepseek-project/ ├── main.js # 主程序 ├── package.json # 项目配置文件 └── conversation.txt # 对话记录文件
1.3 安装依赖
在项目目录下打开命令行,执行:
# 安装项目依赖 npm install # 如果出现权限问题,可以尝试: sudo npm install # linux/mac # 或 npm install --force # windows
此命令会安装 package.json 中定义的所有依赖项:
- axios: 用于发送 http 请求
- moment: 用于时间格式化
如果安装过程中遇到网络问题,可以尝试使用国内镜像:
# 设置淘宝镜像 npm config set registry https://registry.npmmirror.com # 然后重新安装 npm install
1.4 运行程序
安装完依赖后,使用以下命令启动程序:
# 使用 npm 启动 npm start # 或者直接使用 node node main.js
如果遇到权限问题:
# linux/mac sudo npm start # windows (以管理员身份运行命令提示符) npm start
2. 完整代码实现
2.1 package.json
{ "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" } }
2.2 main.js
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);
3. 代码详解
3.1 类结构
deepseekchat
: 主类,封装所有功能constructor
: 构造函数,初始化配置savetofile
: 异步保存对话记录chat
: 主对话循环
3.2 关键功能
文件操作
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); } } } });
3.3 参数说明
model
: 使用的模型名称stream
: 启用流式输出max_tokens
: 最大输出长度 (2048)temperature
: 控制随机性 (0.7)top_p
,top_k
: 采样参数frequency_penalty
: 重复惩罚系数
4. 错误处理
代码包含完整的错误处理机制:
- 网络请求错误处理
- json 解析错误处理
- 文件操作错误处理
- 优雅退出处理
5. 使用方法
5.1 安装依赖
在项目目录下打开命令行,执行:
# 安装项目依赖 npm install # 如果出现权限问题,可以尝试: sudo npm install # linux/mac # 或 npm install --force # windows
此命令会安装 package.json 中定义的所有依赖项:
- axios: 用于发送 http 请求
- moment: 用于时间格式化
如果安装过程中遇到网络问题,可以尝试使用国内镜像:
# 设置淘宝镜像 npm config set registry https://registry.npmmirror.com # 然后重新安装 npm install
5.2 修改配置
在 main.js
中替换 your_api_key
为你的实际 api key。
5.3 运行程序
安装完依赖后,使用以下命令启动程序:
# 使用 npm 启动 npm start # 或者直接使用 node node main.js
如果遇到权限问题:
# linux/mac sudo npm start # windows (以管理员身份运行命令提示符) npm start
5.4 交互方式
- 输入问题进行对话
- 输入 ‘q’ 退出程序
- 查看 conversation.txt 获取对话记录
6. 性能优化建议
内存管理
- 使用流式处理大数据
- 及时清理事件监听器
- 避免内存泄漏
错误处理
- 实现重试机制
- 添加超时处理
- 优雅降级策略
并发控制
- 限制并发请求数
- 实现请求队列
- 添加速率限制
总结
node.js 版本的 deepseek api 实现充分利用了异步编程特性,提供了流畅的对话体验和完善的错误处理机制。代码结构清晰,易于维护和扩展。
以上就是node.js调用deepseek api完整指南的详细内容,更多关于node.js调用deepseek api的资料请关注代码网其它相关文章!
发表评论