这篇文章以 Vuepress 文档接入 Deepseek 来总结文章为例,介绍接入 Deepseek 的流程。
一、注册 DeepSeek 并获取API密钥
- 访问DeepSeek 官网注册登录账号
- 获取API Key(通常以
sk-
开头) - 记录API端点(Endpoint URL,如
https://api.deepseek.com/v1/chat/completions
)
二、使用 Serverless 函数代理 API 请求
因为是静态网站无后端服务器的场景,所以选择 通过 Vercel 免费平台部署一个"无服务器函数",隐藏 API Key。
- 注册 Vercel :访问 Vercel 官网,用 GitHub 账号登录
- 新建项目 :选择"Create a New Project",导入你的 VuePress 博客仓库,修改部署配置,添加环境变量 DEEPSEEK_API_KEY
- 创建 Serverless 函数 :在项目根目录新建
api/summarize.js
文件(Vercel 会自动识别并部署为 Serverless 函数)
js
export default async (req, res) => {
// --------------- CORS 配置 ---------------
const allowedOrigins = ["http://localhost:8080", "https://mmmying.github.io"];
const origin = req.headers.origin;
const isOriginAllowed = allowedOrigins.includes(origin);
// 设置 CORS 头的辅助函数,避免重复代码
const setCorsHeaders = () => {
res.setHeader("Access-Control-Allow-Origin", isOriginAllowed ? origin : "");
res.setHeader("Access-Control-Allow-Methods", "POST, OPTIONS");
res.setHeader("Access-Control-Allow-Headers", "Content-Type");
};
// --------------- 处理 OPTIONS 预检请求 ---------------
if (req.method === "OPTIONS") {
setCorsHeaders();
return res.status(200).end();
}
// --------------- 处理 POST 请求 ---------------
if (req.method === "POST") {
try {
// 验证来源
if (!isOriginAllowed) {
setCorsHeaders();
return res.status(403).json({ error: "非法来源" });
}
// 解析请求体
const { content } = req.body;
if (!content || content.length > 30000) {
setCorsHeaders();
return res.status(400).json({ error: "无效内容" });
}
// 调用 DeepSeek API
const apiResponse = await fetch("https://api.deepseek.com/v1/chat/completions", {
method: "POST",
headers: {
Authorization: `Bearer ${process.env.DEEPSEEK_API_KEY}`,
"Content-Type": "application/json"
},
body: JSON.stringify({
model: "deepseek-chat",
messages: [
{
role: "user",
content: `用中文总结以下技术内容:\n\n${content.slice(0, 3000)}`
}
]
})
});
console.log("deepseek apiResponse: ", apiResponse)
if (!apiResponse.ok) throw new Error("API 调用失败");
const { choices } = await apiResponse.json();
const summary = choices[0].message.content.replace(/\n/g, "<br>");
// 成功响应
setCorsHeaders();
return res.status(200).json({ summary });
} catch (error) {
// 错误响应
console.error("Error:", error);
setCorsHeaders();
return res.status(500).json({ error: "摘要生成失败" });
}
}
// --------------- 其他请求方法处理 ---------------
setCorsHeaders();
return res.status(405).json({ error: "不允许的请求方法" });
};
将代码提交至远程仓库,Vercel 会自动识别并部署为 Serverless 函数。
三、前端集成
在博客文章页添加摘要展示区域,异步调用后端接口。
因为在 VuePress v2 中,.vuepress/components/ 下的文件不会被自动注册为 Vue 组件,需使用 @vuepress/plugin-register-components 。
- 安装依赖
sql
pnpm add @vuepress/plugin-register-components
- 配置插件
在 .vuepress/config.js 中配置插件,指定组件目录:
js
import { path } from "@vuepress/utils";
module.exports = {
plugins: [
[
'@vuepress/plugin-register-components',
{
// 自动注册 components 目录下的所有 Vue 组件
componentsDir: path.resolve(__dirname, './components')
}
]
]
};
- 创建组件
创建 docs/.vuepress/components/Post.vue
,组件中异步调用后端接口:
html
<template>
<div class="article">
<!-- 添加摘要容器 -->
<div v-if="summary" class="summary">
<h3>AI 摘要</h3>
<div v-html="summary"></div>
</div>
<div v-else class="loading">生成摘要中...</div>
<!-- 文章内容, Content 是内置组件 -->
<!-- <Content /> -->
</div>
</template>
<script setup>
import { ref, onMounted } from 'vue';
const summary = ref(null);
// 生成摘要的方法
async function generateSummary() {
try {
// 获取文章纯文本内容(需根据实际结构调整选择器)
const content = document.querySelector('.vp-page').innerText;
const response = await fetch('https://how-browsers-work.vercel.app/api/summarize', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ content })
});
const data = await response.json();
console.log('response data', data);
summary.value = data.summary.replace(/\n/g, '<br>'); // 换行处理
} catch (error) {
console.error('摘要生成失败:', error);
}
}
onMounted(() => {
generateSummary();
})
</script>
<style>
.summary { background: #f8f9fa; padding: 1rem; border-radius: 8px; }
.loading { color: #666; font-style: italic; }
</style>
- 使用组件,在页面中生成摘要
组件要放在 Frontmatter 之后:
yaml
---
lang: zh-CN
title: 01 | Chrome架构:仅仅打开了1个页面,为什么有4个进程?
---
<Post></Post>
四、访问页面
发现有了显示摘要的地方,但摘要生成失败,在 Vercel 的日志中查看,发现 DeepSeek 返回错误码 402,这是账号余额不足的问题。看了看钱包,我就不浪费这个钱了,主要是为了跑通接入这个流程,这其实就相当于接入 DeepSeek 成功了。