Node.js 调用 DeepSeek API 完整指南

简介

本文将介绍如何使用 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 安装依赖

在项目目录下打开命令行,执行:

bash 复制代码
# 安装项目依赖
npm install

# 如果出现权限问题,可以尝试:
sudo npm install  # Linux/Mac
# 或
npm install --force  # Windows

此命令会安装 package.json 中定义的所有依赖项:

  • axios: 用于发送 HTTP 请求
  • moment: 用于时间格式化

如果安装过程中遇到网络问题,可以尝试使用国内镜像:

bash 复制代码
# 设置淘宝镜像
npm config set registry https://registry.npmmirror.com

# 然后重新安装
npm install

1.4 运行程序

安装完依赖后,使用以下命令启动程序:

bash 复制代码
# 使用 npm 启动
npm start

# 或者直接使用 node
node main.js

如果遇到权限问题:

bash 复制代码
# Linux/Mac
sudo npm start

# Windows (以管理员身份运行命令提示符)
npm start

2. 完整代码实现

2.1 package.json

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

javascript 复制代码
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 关键功能

文件操作
javascript 复制代码
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);
}
流式处理
javascript 复制代码
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 安装依赖

在项目目录下打开命令行,执行:

bash 复制代码
# 安装项目依赖
npm install

# 如果出现权限问题,可以尝试:
sudo npm install  # Linux/Mac
# 或
npm install --force  # Windows

此命令会安装 package.json 中定义的所有依赖项:

  • axios: 用于发送 HTTP 请求
  • moment: 用于时间格式化

如果安装过程中遇到网络问题,可以尝试使用国内镜像:

bash 复制代码
# 设置淘宝镜像
npm config set registry https://registry.npmmirror.com

# 然后重新安装
npm install

5.2 修改配置

main.js 中替换 YOUR_API_KEY 为你的实际 API Key。

5.3 运行程序

安装完依赖后,使用以下命令启动程序:

bash 复制代码
# 使用 npm 启动
npm start

# 或者直接使用 node
node main.js

如果遇到权限问题:

bash 复制代码
# Linux/Mac
sudo npm start

# Windows (以管理员身份运行命令提示符)
npm start

5.4 交互方式

  1. 输入问题进行对话
  2. 输入 'q' 退出程序
  3. 查看 conversation.txt 获取对话记录

6. 性能优化建议

  1. 内存管理

    • 使用流式处理大数据
    • 及时清理事件监听器
    • 避免内存泄漏
  2. 错误处理

    • 实现重试机制
    • 添加超时处理
    • 优雅降级策略
  3. 并发控制

    • 限制并发请求数
    • 实现请求队列
    • 添加速率限制

总结

Node.js 版本的 DeepSeek API 实现充分利用了异步编程特性,提供了流畅的对话体验和完善的错误处理机制。代码结构清晰,易于维护和扩展。

立即体验

想要体验 DeepSeek 的强大功能?现在就开始吧!

快来体验 DeepSeek:https://cloud.siliconflow.cn/i/vnCCfVaQ

快来体验 DeepSeek:https://cloud.siliconflow.cn/i/vnCCfVaQ

快来体验 DeepSeek:https://cloud.siliconflow.cn/i/vnCCfVaQ

相关推荐
李游Leo6 小时前
M系列/Mac安装配置Node.js全栈开发环境(nvm+npm+yarn)
macos·npm·node.js
山禾女鬼0016 小时前
NPM 的扁平化目录与幻影依赖问题,以及 PNPM 如何通过硬链接和软链接解决
前端·npm·node.js
浏览器爱好者7 小时前
如何使用Webpack构建前端应用?
前端·webpack·node.js
Ellen翔11 小时前
npx tailwindcss init报错npm error could not determine executable to run
前端·npm·node.js
27669582921 天前
新版231普通阿里滑块 自动化和逆向实现 分析
java·python·node.js·自动化·go·231滑块·阿里231
智驾2 天前
Node.js与嵌入式开发:打破界限的创新结合
node.js·嵌入式
yqcoder2 天前
Node 服务器数据响应类型处理
运维·服务器·前端·javascript·node.js
Amd7942 天前
Node.js 与 PostgreSQL 集成:深入 pg 模块的应用与实践
postgresql·性能优化·node.js·最佳实践·web 开发·数据库集成·pg 模块
kongxx2 天前
使用mockttp库模拟HTTP服务器和客户端进行单元测试
单元测试·node.js