简介
本文将介绍如何使用 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