简介:本文详细介绍如何将DeepSeek AI服务集成至个人网站,涵盖环境准备、API调用、前端交互、错误处理及性能优化全流程,提供可复制的代码示例与实用建议。
axios(HTTP请求库)和express(后端框架示例),Python环境需安装requests库。
npm init -y && npm install axios expresspip install requests
API_KEY,建议将密钥存储在环境变量中(如.env文件)。/v1/chat/completions:对话生成/v1/embeddings:文本向量化Authorization和Content-Type字段要求。
const express = require('express');const axios = require('axios');const app = express();app.use(express.json());const DEEPSEEK_API_KEY = process.env.DEEPSEEK_API_KEY;const DEEPSEEK_ENDPOINT = 'https://api.deepseek.com/v1/chat/completions';app.post('/api/deepseek', async (req, res) => {try {const { prompt, model = 'deepseek-chat' } = req.body;const response = await axios.post(DEEPSEEK_ENDPOINT,{model,messages: [{ role: 'user', content: prompt }],temperature: 0.7},{headers: {'Authorization': `Bearer ${DEEPSEEK_API_KEY}`,'Content-Type': 'application/json'}});res.json(response.data.choices[0].message);} catch (error) {console.error('DeepSeek API Error:', error.response?.data || error.message);res.status(500).json({ error: '服务调用失败' });}});app.listen(3000, () => console.log('Server running on port 3000'));
deepseek-chat(通用对话)、deepseek-code(代码生成)等,需根据场景选择。temperature值范围0-1,值越高生成结果越具创造性。messages数组维护对话历史,需限制总token数(如4096)避免超限。
<!DOCTYPE html><html><head><title>DeepSeek 集成示例</title><style>#chat-container { width: 600px; margin: 0 auto; }#messages { height: 400px; border: 1px solid #ccc; padding: 10px; overflow-y: auto; }#user-input { width: 80%; padding: 8px; }#submit-btn { width: 18%; padding: 8px; }</style></head><body><div id="chat-container"><div id="messages"></div><input type="text" id="user-input" placeholder="输入问题..."><button id="submit-btn">发送</button></div><script>document.getElementById('submit-btn').addEventListener('click', async () => {const input = document.getElementById('user-input');const messagesDiv = document.getElementById('messages');const userMessage = input.value.trim();if (!userMessage) return;// 显示用户消息messagesDiv.innerHTML += `<div><strong>你:</strong> ${userMessage}</div>`;input.value = '';try {// 调用后端APIconst response = await fetch('/api/deepseek', {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify({ prompt: userMessage })});const data = await response.json();messagesDiv.innerHTML += `<div><strong>AI:</strong> ${data.content}</div>`;messagesDiv.scrollTop = messagesDiv.scrollHeight;} catch (error) {messagesDiv.innerHTML += `<div style="color:red">错误: ${error.message}</div>`;}});</script></body></html>
stream: true参数。prompt参数进行长度限制(如512字符)和敏感词过滤。express-rate-limit中间件防止API滥用:
const rateLimit = require('express-rate-limit');app.use(rateLimit({windowMs: 15 * 60 * 1000, // 15分钟max: 100 // 每个IP限制100次请求}));
const proxyAgent = new HttpsProxyAgent('http://proxy-server:port');axios.post(DEEPSEEK_ENDPOINT, data, { httpsAgent: proxyAgent });
const response = await axios.post(DEEPSEEK_ENDPOINT, data, {timeout: 30000,// 其他配置...});
async function callDeepSeek(prompt, retries = 3) {try {const response = await axios.post(...); // 同上return response;} catch (error) {if (retries <= 0) throw error;await new Promise(resolve => setTimeout(resolve, 1000));return callDeepSeek(prompt, retries - 1);}}
FROM node:16-alpineWORKDIR /appCOPY package*.json ./RUN npm installCOPY . .EXPOSE 3000CMD ["node", "server.js"]
构建并运行:
docker build -t deepseek-integration .docker run -d -p 3000:3000 -e DEEPSEEK_API_KEY=your_key deepseek-integration
winston记录请求日志:
const winston = require('winston');const logger = winston.createLogger({transports: [new winston.transports.File({ filename: 'deepseek.log' })]});// 在catch块中添加:logger.error('DeepSeek Error:', error);
通过以上步骤,开发者可系统化地将DeepSeek功能嵌入个人网站,构建智能交互体验。实际开发中需根据具体业务场景调整参数和架构,建议先在测试环境验证功能,再逐步上线。”