Node.js接入DeepSeek實現(xiàn)流式對話功能
準(zhǔn)備工作
1. 獲取API Key
首先,您需要在DeepSeek官網(wǎng)注冊賬號并創(chuàng)建一個項目來獲取API Key。這個Key將用于驗證您的請求。
2. 安裝依賴
確保你的Node.js環(huán)境已準(zhǔn)備就緒,并安裝以下npm包:
npm install axios express http
實現(xiàn)步驟
1. 創(chuàng)建Express服務(wù)器
我們將使用Express框架快速搭建一個HTTP服務(wù)器。以下是基本設(shè)置代碼片段:
const express = require('express'); const app = express(); app.use(express.json()); // 定義主機名和端口 const hostname = '127.0.0.1'; const port = 3002;
2. 配置CORS中間件
為了允許跨域請求,我們需要添加CORS支持:
app.all('*', function (req, res, next) { // CORS headers setup... res.header('Access-Control-Allow-Origin', '*'); // 允許任意域名發(fā)起跨域請求 res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With'); // 允許指定的頭部字段 res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS'); // 允許指定的 HTTP 方法 res.header('X-Powered-By', '3.2.1'); // 添加自定義頭部信息 if ('OPTIONS' == req.method) { // 如果請求方法是 OPTIONS,則直接返回成功響應(yīng) res.send(200); } else { // 否則繼續(xù)處理請求 next(); } });
3. 定義路由處理函數(shù)
接下來,定義處理/chat/completions
請求的路由,這里我們采用流式響應(yīng)方式處理數(shù)據(jù)返回:
router.get('/chat/completions', async (req, res) => { let messages = [{ role: "user", content: req.query.mesage}] let { config } = await createChatCompletion(messages) let response = await axios(config) res.setHeader('Content-Type', 'text/event-stream'); res.setHeader('Cache-Control', 'no-cache'); res.setHeader('Connection', 'keep-alive'); // 處理流式響應(yīng) response.data.on('data', async (chunk) => { const lines = chunk.toString().split('\n'); // 將數(shù)據(jù)塊轉(zhuǎn)換為字符串并按行分割 for (const line of lines) { if (line.trim() === '') continue; // 跳過空行 if (line.trim() === 'data: [DONE]') continue; // 跳過結(jié)束標(biāo)記 if (line.startsWith('data:')) { // 檢查是否以 "data: " 開頭 try { const json = JSON.parse(line.slice(6)); // 去掉前綴 "data: " 并解析 JSON if (json.choices[0].delta.content) { // 檢查是否有內(nèi)容 let contents = [] let index = 0 contents.push(json.choices[0].delta.content) for (let i = 0; i < contents.length; i++) { setTimeout(() => { res.write(`data: ${JSON.stringify({ content: contents[index] })}\n\n`); index++ }, 200); } } } catch (e) { continue; // 如果解析失敗,繼續(xù)處理下一行 } } } }); // 處理邏輯... });
4. 調(diào)用DeepSeek API
編寫輔助函數(shù)createChatCompletion
來構(gòu)造請求參數(shù)并調(diào)用DeepSeek API:
async function createChatCompletion(messages) { const data = JSON.stringify({ "messages": messages, "model": "deepseek-reasoner", "response_format": {"type":"text"}, "stream": true, }); let config = { method: 'post', url: 'https://api.deepseek.com/chat/completions', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer YOUR_API_KEY`, }, responseType: "stream", data: data }; return {config}; }
請記得替換YOUR_API_KEY
為您的實際API密鑰。
5. 啟動服務(wù)器
最后,啟動Express服務(wù)器監(jiān)聽指定端口:
app.listen(PORT, HOSTNAME, () => { console.log(`Server running at http://${HOSTNAME}:${PORT}/`); });
前端處理
Server-Sent Events(SSE)是一種用于實現(xiàn)服務(wù)器向客戶端單向推送數(shù)據(jù)的技術(shù)。使用了 SSE 來實現(xiàn)客戶端與服務(wù)器之間的實時通信。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Server-Sent Events Example</title> </head> <body> <h1>與deepseek聊天</h1> <div> <textarea id="userInput" placeholder="輸入你的消息..." rows="4" cols="50"></textarea><br /> <button onclick="sendMessage()">發(fā)送消息</button> </div> <div id="messages"> <!-- 服務(wù)器返回的消息將顯示在這里 --> </div> <script> function sendMessage () { const responseArea = document.getElementById('messages'); const userInput = document.getElementById('userInput').value; let p = document.createElement('p') const div = document.createElement('div') div.classList = 'title' div.innerHTML = userInput responseArea.appendChild(div) if (!userInput) return; // 創(chuàng)建一個新的 EventSource 對象 const eventSource = new EventSource(`http://127.0.0.1:3002/chat/completions?mesage=${userInput}`); // 監(jiān)聽 'message' 事件,每當(dāng)服務(wù)器推送一條新消息時觸發(fā) eventSource.onmessage = function (event) { try { const json = JSON.parse(event.data); updateResponseArea(json.content, p); } catch (e) { console.error('Error parsing JSON:', e); } }; // 監(jiān)聽 'open' 事件,表示連接已成功打開 eventSource.onopen = function () { console.log('Connection to server opened.'); }; // 監(jiān)聽 'error' 事件,處理任何錯誤或連接中斷的情況 eventSource.onerror = function (error) { if (eventSource.readyState === EventSource.CLOSED) { console.log('Connection was closed by the server.'); } else { console.error('EventSource failed:', error); } eventSource.close(); // 手動關(guān)閉連接 }; // 更新頁面上的響應(yīng)區(qū)域 function updateResponseArea (message, p) { p.classList = 'back' p.innerHTML += `<span>${message}</span>`; responseArea.appendChild(p) } } </script> </body> </html>
結(jié)論
通過以上步驟,您已經(jīng)成功地使用Node.js集成了DeepSeek的聊天完成API。這不僅能夠增強應(yīng)用程序的功能性,還能提供更加智能化的用戶體驗。希望這篇指南能幫助您順利接入DeepSeek服務(wù),開啟探索AI之旅!
效果
由于無法放置視頻,流式效果無法展現(xiàn)
請注意,上述代碼示例基于您提供的代碼進(jìn)行了簡化和抽象,旨在提供一個清晰的流程說明。實際開發(fā)時,請根據(jù)自己的需求進(jìn)行調(diào)整和優(yōu)化。
以上就是Node.js接入DeepSeek實現(xiàn)流式對話功能的詳細(xì)內(nèi)容,更多關(guān)于Node.js DeepSeek流式對話的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Node.js 文件夾目錄結(jié)構(gòu)創(chuàng)建實例代碼
下面小編就為大家?guī)硪黄狽ode.js 文件夾目錄結(jié)構(gòu)創(chuàng)建實例代碼。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2016-07-07node.js利用mongoose獲取mongodb數(shù)據(jù)的格式化問題詳解
這篇文章主要給大家介紹了關(guān)于node.js利用mongoose獲取mongodb數(shù)據(jù)的格式化問題,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)把。2017-10-10