中文亚洲精品无码_熟女乱子伦免费_人人超碰人人爱国产_亚洲熟妇女综合网

當前位置: 首頁 > news >正文

免費域名x網(wǎng)站怎么學seo基礎

免費域名x網(wǎng)站,怎么學seo基礎,做漫畫封面的網(wǎng)站,蘇州企業(yè)網(wǎng)站建文章目錄 前言一、demo演示二、node.js 使用步驟1.引入庫2.引入包 前端HTML調(diào)用接口和UI所有文件總結 前言 關注博主,學習每天一個小demo 今天是Ai對話網(wǎng)站 又到了每天一個小demo的時候咯,前面我寫了多人實時對話demo、和視頻轉(zhuǎn)換demo,今天…

文章目錄

  • 前言
  • 一、demo演示
  • 二、node.js 使用步驟
    • 1.引入庫
    • 2.引入包
  • 前端HTML調(diào)用接口和UI
  • 所有文件
  • 總結


前言

關注博主,學習每天一個小demo 今天是Ai對話網(wǎng)站

又到了每天一個小demo的時候咯,前面我寫了多人實時對話demo、和視頻轉(zhuǎn)換demo,今天我來使用 node.js + html 調(diào)用chatGpt Api實現(xiàn)一個Ai 流式對話小demo,當然現(xiàn)在主流的各種APi調(diào)用方式一致,你也可以接入deepseek,或者第三方的接口,效果一樣


一、demo演示

下面是一個簡單的demo演示,并且是支持流式的
在這里插入圖片描述

二、node.js 使用步驟

1.引入庫

代碼如下:

先初始化一個package.js 文件。

npm init -y

我們需要安裝 express、cors、openAi、dotenv三方庫

{"name": "web","version": "1.0.0","main": "server.js","scripts": {"test": "echo \"Error: no test specified\" && exit 1","start": "node server.js"},"keywords": [],"author": "","license": "ISC","description": "","dependencies": {"axios": "^1.7.9","cors": "^2.8.5","dotenv": "^16.0.3","express": "^4.18.2","openai": "^4.0.0"}
}

2.引入包

創(chuàng)建server.js 引入我們的第三方包 編寫接口邏輯

**特別關注:

  1. baseURL: 這里大家可以替換其他的APi 比如deepseek(好像目前不能充值了),或者一些第三方的API地址。
  2. apiKey: 這里大家把key可以直接填寫上,我這里為了學習知識,新建了一個.env 文件。**
const express = require('express');
const cors = require('cors');
const OpenAI = require('openai');
require('dotenv').config();const app = express();
app.use(express.json());
app.use(cors());// 初始化OpenAI客戶端
const openai = new OpenAI({apiKey: process.env.DEEPSEEK_API_KEY, baseURL: "https://api.openai.com/v1"  // 使用OpenAI官方API地址  這里可以可以使用別的Api地址// 比如 deepseek 或者其他的第三方的一些// baseURL: "https://api.deepseek.com/v1"
});let conversationHistory = [];app.post('/chat', async (req, res) => {try {const { message } = req.body;// 設置響應頭,支持流式輸出res.setHeader('Content-Type', 'text/event-stream');res.setHeader('Cache-Control', 'no-cache');res.setHeader('Connection', 'keep-alive');res.setHeader('Access-Control-Allow-Origin', '*');  // 添加CORS支持// 添加用戶消息到歷史記錄conversationHistory.push({ role: "user", content: message });const stream = await openai.chat.completions.create({model: "gpt-3.5-turbo",messages: [{ role: "system", content: "You are a helpful assistant." },...conversationHistory],temperature: 0.7,max_tokens: 1000,stream: true,});let fullResponse = '';// 確保每次寫入后立即刷新緩沖區(qū)for await (const chunk of stream) {const content = chunk.choices[0]?.delta?.content || '';if (content) {fullResponse += content;const dataToSend = JSON.stringify({ content });console.log('Sending to client:', dataToSend);res.write(`data: ${dataToSend}\n\n`);// 強制刷新緩沖區(qū)if (res.flush) {res.flush();}}}// 將完整回復添加到對話歷史conversationHistory.push({ role: "assistant", content: fullResponse });if (conversationHistory.length > 10) {conversationHistory = conversationHistory.slice(-10);}res.write('data: [DONE]\n\n');if (res.flush) {res.flush();}res.end();} catch (error) {console.error('Error:', error);res.write(`data: ${JSON.stringify({ error: '服務器錯誤' })}\n\n`);res.end();}
});const PORT = 3000;
app.listen(PORT, () => {console.log(`服務器運行在端口 ${PORT}`);
}); 

在根目錄執(zhí)行 node server.js 啟動服務

前端HTML調(diào)用接口和UI

不墨跡哈,直接把所有代碼貼過來 大家好直接研究代碼,我就不用一行一行解讀了,沒啥東西,難處就是對流式數(shù)據(jù)的一個處理

特別注意, 不要直接點擊html打開頁面,在vscode里面安裝擴展Live Server,然后點擊右下角 Go live啟動一個微服務。
在這里插入圖片描述
在這里插入圖片描述

<!DOCTYPE html>
<html lang="zh">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>ChatGPT 聊天</title><style>#chat-container {width: 80%;max-width: 800px;margin: 20px auto;padding: 20px;border: 1px solid #ccc;border-radius: 5px;}#chat-messages {height: 400px;overflow-y: auto;margin-bottom: 20px;padding: 10px;border: 1px solid #eee;}.message {margin: 10px 0;padding: 10px;border-radius: 5px;}.user-message {background-color: #e3f2fd;margin-left: 20%;}.bot-message {background-color: #f5f5f5;margin-right: 20%;}#message-form {display: flex;gap: 10px;}#message-input {flex: 1;padding: 8px;}.typing {opacity: 0.5;}.cursor {display: inline-block;width: 2px;height: 15px;background: #000;margin-left: 2px;animation: blink 1s infinite;}@keyframes blink {0%, 100% { opacity: 1; }50% { opacity: 0; }}</style>
</head>
<body><div id="chat-container"><div id="chat-messages"></div><form id="message-form"><input type="text" id="message-input" placeholder="輸入消息..." required><button type="submit" id="submit-btn">發(fā)送</button></form></div><script>const messageForm = document.getElementById('message-form');const messageInput = document.getElementById('message-input');const chatMessages = document.getElementById('chat-messages');const submitBtn = document.getElementById('submit-btn');messageForm.addEventListener('submit', async (e) => {e.preventDefault();const message = messageInput.value.trim();if (!message) return;// 禁用輸入和發(fā)送按鈕messageInput.disabled = true;submitBtn.disabled = true;// 顯示用戶消息addMessage(message, 'user');messageInput.value = '';// 創(chuàng)建機器人回復的消息框const botMessageDiv = document.createElement('div');botMessageDiv.className = 'message bot-message typing';chatMessages.appendChild(botMessageDiv);// 添加光標const cursor = document.createElement('span');cursor.className = 'cursor';botMessageDiv.appendChild(cursor);try {const response = await fetch('http://localhost:3000/chat', {method: 'POST',headers: {'Content-Type': 'application/json','Accept': 'text/event-stream'},body: JSON.stringify({ message })});if (!response.ok) {throw new Error(`HTTP error! status: ${response.status}`);}const reader = response.body.getReader();const decoder = new TextDecoder();let botResponse = '';let buffer = '';try {while (true) {const { value, done } = await reader.read();// 如果流結束了,就退出循環(huán)if (done) {console.log('Stream complete');break;}// 確保有值才處理if (value) {buffer += decoder.decode(value, { stream: true });const lines = buffer.split('\n');// 保留最后一個不完整的行buffer = lines.pop() || '';for (const line of lines) {if (line.trim() === '') continue;if (!line.startsWith('data: ')) continue;const data = line.slice(6).trim();if (data === '[DONE]') {botMessageDiv.classList.remove('typing');cursor.remove();continue;}try {const parsedData = JSON.parse(data);if (parsedData.content) {botResponse += parsedData.content;botMessageDiv.textContent = botResponse;botMessageDiv.appendChild(cursor);chatMessages.scrollTop = chatMessages.scrollHeight;}} catch (e) {console.error('JSON解析錯誤:', e, 'Raw data:', data);}}}}// 處理最后可能殘留的數(shù)據(jù)if (buffer.trim()) {const finalText = decoder.decode(); // 完成流的解碼if (finalText) {buffer += finalText;const lines = buffer.split('\n');for (const line of lines) {if (line.trim() === '' || !line.startsWith('data: ')) continue;const data = line.slice(6).trim();if (data === '[DONE]') continue;try {const parsedData = JSON.parse(data);if (parsedData.content) {botResponse += parsedData.content;botMessageDiv.textContent = botResponse;}} catch (e) {console.error('最終解析錯誤:', e, 'Raw data:', data);}}}}} catch (streamError) {console.error('Stream processing error:', streamError);throw streamError;}} catch (error) {console.error('Error:', error);botMessageDiv.textContent = '抱歉,發(fā)生錯誤。';botMessageDiv.classList.remove('typing');cursor.remove();} finally {messageInput.disabled = false;submitBtn.disabled = false;messageInput.focus();}});function addMessage(text, sender) {const messageDiv = document.createElement('div');messageDiv.className = `message ${sender}-message`;messageDiv.textContent = text;chatMessages.appendChild(messageDiv);chatMessages.scrollTop = chatMessages.scrollHeight;}</script>
</body>
</html> 

所有文件

  1. .env 存儲了APi-key
  2. index.html 前端代碼
  3. server.js 后段代碼
    在這里插入圖片描述
    在這里插入圖片描述

總結

盡可能的多學習一些知識,或許以后用不到,關注我每天練習一個小demo。

http://m.risenshineclean.com/news/63146.html

相關文章:

  • 淄博網(wǎng)站建設專家湖北短視頻seo營銷
  • 哈爾濱網(wǎng)站建設價格企業(yè)文化墻
  • 個人站長做網(wǎng)站seo網(wǎng)站優(yōu)化培訓找哪些
  • 做百科權威網(wǎng)站有哪些淘寶關鍵詞優(yōu)化技巧
  • 建設微信網(wǎng)站的流程圖青島seo外包公司
  • 網(wǎng)站制作字怎么放在圖上面策劃公司排行榜
  • 龍巖到永定seo技術大師
  • 建站工具搭建前臺網(wǎng)站seo關鍵詞優(yōu)化排名
  • 安慶網(wǎng)站設計百度拍照搜索
  • vs2015 asp網(wǎng)站開發(fā)360優(yōu)化大師app
  • php網(wǎng)站模板網(wǎng)站排名首頁前三位
  • wordpress h1標簽優(yōu)化福州seo
  • 臺州seo網(wǎng)站推廣費用昆明seo排名
  • 簡單網(wǎng)站制作實例網(wǎng)絡營銷品牌案例
  • 專業(yè)網(wǎng)站建設制作價格網(wǎng)絡營銷師培訓費用是多少
  • 網(wǎng)站排版設計欣賞哈爾濱網(wǎng)站優(yōu)化流程
  • 優(yōu)設網(wǎng)專利廣西網(wǎng)絡優(yōu)化seo
  • 商丘做網(wǎng)站用什么程序全網(wǎng)營銷系統(tǒng)是不是傳銷
  • 微信公眾號模板無錫seo公司
  • 地圖網(wǎng)站模板google adwords
  • 太原商城網(wǎng)站建設啦啦啦資源視頻在線觀看8
  • 新的網(wǎng)絡營銷方法天津seo培訓
  • 常州做網(wǎng)站找哪家好寧波seo優(yōu)化公司
  • 電子商務專業(yè)是學什么的做網(wǎng)站怎么優(yōu)化
  • 17網(wǎng)站一起做網(wǎng)店 每日新款阿里大數(shù)據(jù)平臺
  • 建網(wǎng)站新科網(wǎng)站建設泰州百度公司代理商
  • 調(diào)用其他網(wǎng)站文章列表網(wǎng)絡營銷自學網(wǎng)站
  • 一個網(wǎng)站的設計思路百度開戶渠道商哪里找
  • 網(wǎng)站建設售后如何進行網(wǎng)絡推廣營銷
  • 邢臺企業(yè)網(wǎng)站制作建設關鍵詞查詢神器