Node.js調(diào)用DeepSeek?API的完整指南
簡(jiǎn)介
本文將介紹如何使用 Node.js 調(diào)用 DeepSeek API,實(shí)現(xiàn)流式對(duì)話并保存對(duì)話記錄。Node.js 版本使用現(xiàn)代異步編程方式實(shí)現(xiàn),支持流式處理和錯(cuò)誤處理。
1. 環(huán)境準(zhǔn)備
1.1 系統(tǒng)要求
- Node.js 14.0 或更高版本
- npm 包管理器
1.2 項(xiàng)目結(jié)構(gòu)
deepseek-project/ ├── main.js # 主程序 ├── package.json # 項(xiàng)目配置文件 └── conversation.txt # 對(duì)話記錄文件
1.3 安裝依賴
在項(xiàng)目目錄下打開(kāi)命令行,執(zhí)行:
# 安裝項(xiàng)目依賴 npm install # 如果出現(xiàn)權(quán)限問(wèn)題,可以嘗試: sudo npm install # Linux/Mac # 或 npm install --force # Windows
此命令會(huì)安裝 package.json 中定義的所有依賴項(xiàng):
- axios: 用于發(fā)送 HTTP 請(qǐng)求
- moment: 用于時(shí)間格式化
如果安裝過(guò)程中遇到網(wǎng)絡(luò)問(wèn)題,可以嘗試使用國(guó)內(nèi)鏡像:
# 設(shè)置淘寶鏡像 npm config set registry https://registry.npmmirror.com # 然后重新安裝 npm install
1.4 運(yùn)行程序
安裝完依賴后,使用以下命令啟動(dòng)程序:
# 使用 npm 啟動(dòng) npm start # 或者直接使用 node node main.js
如果遇到權(quán)限問(wèn)題:
# Linux/Mac sudo npm start # Windows (以管理員身份運(yùn)行命令提示符) npm start
2. 完整代碼實(shí)現(xiàn)
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 封裝問(wèn)題輸入 const question = (prompt) => new Promise((resolve) => rl.question(prompt, resolve)); try { while (true) { const userInput = await question('\n請(qǐng)輸入您的問(wèn)題 (輸入 q 退出): '); if (userInput.trim().toLowerCase() === 'q') { console.log('程序已退出'); break; } // 保存問(wèn)題 await this.saveToFile(userInput, true); // 準(zhǔn)備請(qǐng)求數(shù)據(jù) 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ā)送流式請(qǐng)求 const response = await axios({ method: 'post', url: this.url, data: data, headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${this.apiKey}` }, responseType: 'stream' }); // 處理流式響應(yīng) 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; } } } }); // 等待響應(yīng)完成 await new Promise((resolve) => { response.data.on('end', async () => { console.log('\n----------------------------------------'); await this.saveToFile('\n----------------------------------------\n'); resolve(); }); }); } catch (error) { const errorMsg = `請(qǐng)求錯(cuò)誤: ${error.message}\n`; console.error(errorMsg); await this.saveToFile(errorMsg); } } } finally { rl.close(); } } } // 運(yùn)行程序 async function main() { const chatbot = new DeepSeekChat(); await chatbot.chat(); } main().catch(console.error);
3. 代碼詳解
3.1 類結(jié)構(gòu)
DeepSeekChat
: 主類,封裝所有功能constructor
: 構(gòu)造函數(shù),初始化配置saveToFile
: 異步保存對(duì)話記錄chat
: 主對(duì)話循環(huán)
3.2 關(guān)鍵功能
文件操作
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 參數(shù)說(shuō)明
model
: 使用的模型名稱stream
: 啟用流式輸出max_tokens
: 最大輸出長(zhǎng)度 (2048)temperature
: 控制隨機(jī)性 (0.7)top_p
,top_k
: 采樣參數(shù)frequency_penalty
: 重復(fù)懲罰系數(shù)
4. 錯(cuò)誤處理
代碼包含完整的錯(cuò)誤處理機(jī)制:
- 網(wǎng)絡(luò)請(qǐng)求錯(cuò)誤處理
- JSON 解析錯(cuò)誤處理
- 文件操作錯(cuò)誤處理
- 優(yōu)雅退出處理
5. 使用方法
5.1 安裝依賴
在項(xiàng)目目錄下打開(kāi)命令行,執(zhí)行:
# 安裝項(xiàng)目依賴 npm install # 如果出現(xiàn)權(quán)限問(wèn)題,可以嘗試: sudo npm install # Linux/Mac # 或 npm install --force # Windows
此命令會(huì)安裝 package.json 中定義的所有依賴項(xiàng):
- axios: 用于發(fā)送 HTTP 請(qǐng)求
- moment: 用于時(shí)間格式化
如果安裝過(guò)程中遇到網(wǎng)絡(luò)問(wèn)題,可以嘗試使用國(guó)內(nèi)鏡像:
# 設(shè)置淘寶鏡像 npm config set registry https://registry.npmmirror.com # 然后重新安裝 npm install
5.2 修改配置
在 main.js
中替換 YOUR_API_KEY
為你的實(shí)際 API Key。
5.3 運(yùn)行程序
安裝完依賴后,使用以下命令啟動(dòng)程序:
# 使用 npm 啟動(dòng) npm start # 或者直接使用 node node main.js
如果遇到權(quán)限問(wèn)題:
# Linux/Mac sudo npm start # Windows (以管理員身份運(yùn)行命令提示符) npm start
5.4 交互方式
- 輸入問(wèn)題進(jìn)行對(duì)話
- 輸入 ‘q’ 退出程序
- 查看 conversation.txt 獲取對(duì)話記錄
6. 性能優(yōu)化建議
內(nèi)存管理
- 使用流式處理大數(shù)據(jù)
- 及時(shí)清理事件監(jiān)聽(tīng)器
- 避免內(nèi)存泄漏
錯(cuò)誤處理
- 實(shí)現(xiàn)重試機(jī)制
- 添加超時(shí)處理
- 優(yōu)雅降級(jí)策略
并發(fā)控制
- 限制并發(fā)請(qǐng)求數(shù)
- 實(shí)現(xiàn)請(qǐng)求隊(duì)列
- 添加速率限制
總結(jié)
Node.js 版本的 DeepSeek API 實(shí)現(xiàn)充分利用了異步編程特性,提供了流暢的對(duì)話體驗(yàn)和完善的錯(cuò)誤處理機(jī)制。代碼結(jié)構(gòu)清晰,易于維護(hù)和擴(kuò)展。
以上就是Node.js調(diào)用DeepSeek API完整指南的詳細(xì)內(nèi)容,更多關(guān)于Node.js調(diào)用DeepSeek API的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Node.js開(kāi)發(fā)靜態(tài)資源服務(wù)器
這篇文章主要為大家介紹了Node.js開(kāi)發(fā)靜態(tài)資源服務(wù)器示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-08-08使用Node.js實(shí)現(xiàn)一個(gè)簡(jiǎn)單的命令行工具
這篇文章主要為大家詳細(xì)介紹了如何用 Node.js 實(shí)現(xiàn)一個(gè)簡(jiǎn)單的命令行工具,模仿常用的 ls 命令,包括其 -a 和 -l 參數(shù)的功能,感興趣的可以了解下2024-11-11將node安裝到其他盤的超詳細(xì)步驟與說(shuō)明
基本現(xiàn)在很多主流的前端框架都用了node.js 但是node裝起來(lái)確實(shí)頭疼,下面這篇文章主要給大家介紹了關(guān)于如何將node安裝到其他盤的超詳細(xì)步驟與說(shuō)明,需要的朋友可以參考下2023-06-06nodejs對(duì)文件中的圖片進(jìn)行歸類操作示例
這篇文章主要為大家介紹了nodejs對(duì)文件中的圖片進(jìn)行歸類的實(shí)現(xiàn)示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-07-07