Node.js調用DeepSeek?API的完整指南
簡介
本文將介紹如何使用 Node.js 調用 DeepSeek API,實現流式對話并保存對話記錄。Node.js 版本使用現代異步編程方式實現,支持流式處理和錯誤處理。
1. 環(huán)境準備
1.1 系統要求
- Node.js 14.0 或更高版本
- npm 包管理器
1.2 項目結構
deepseek-project/ ├── main.js # 主程序 ├── package.json # 項目配置文件 └── conversation.txt # 對話記錄文件
1.3 安裝依賴
在項目目錄下打開命令行,執(zhí)行:
# 安裝項目依賴 npm install # 如果出現權限問題,可以嘗試: sudo npm install # Linux/Mac # 或 npm install --force # Windows
此命令會安裝 package.json 中定義的所有依賴項:
- axios: 用于發(fā)送 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() {
// 創(chuàng)建命令行接口
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 {
// 發(fā)送流式請求
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: 主對話循環(huán)
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 解析錯誤處理
- 文件操作錯誤處理
- 優(yōu)雅退出處理
5. 使用方法
5.1 安裝依賴
在項目目錄下打開命令行,執(zhí)行:
# 安裝項目依賴 npm install # 如果出現權限問題,可以嘗試: sudo npm install # Linux/Mac # 或 npm install --force # Windows
此命令會安裝 package.json 中定義的所有依賴項:
- axios: 用于發(fā)送 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. 性能優(yōu)化建議
內存管理
- 使用流式處理大數據
- 及時清理事件監(jiān)聽器
- 避免內存泄漏
錯誤處理
- 實現重試機制
- 添加超時處理
- 優(yōu)雅降級策略
并發(fā)控制
- 限制并發(fā)請求數
- 實現請求隊列
- 添加速率限制
總結
Node.js 版本的 DeepSeek API 實現充分利用了異步編程特性,提供了流暢的對話體驗和完善的錯誤處理機制。代碼結構清晰,易于維護和擴展。
以上就是Node.js調用DeepSeek API完整指南的詳細內容,更多關于Node.js調用DeepSeek API的資料請關注腳本之家其它相關文章!
相關文章
Node.js發(fā)送HTTP客戶端請求并顯示響應結果的方法示例
這篇文章主要介紹了Node.js發(fā)送HTTP客戶端請求并顯示響應結果的方法,結合完整實例形式分析了nodejs發(fā)送http請求及響應的相關操作技巧,需要的朋友可以參考下2017-04-04

