网页快速接入 Deepseek,是如此简单!分分钟带你搞定!

这篇文章以 Vuepress 文档接入 Deepseek 来总结文章为例,介绍接入 Deepseek 的流程。

一、注册 DeepSeek 并获取API密钥

  1. 访问DeepSeek 官网注册登录账号
  2. 获取API Key(通常以sk-开头)
  3. 记录API端点(Endpoint URL,如https://api.deepseek.com/v1/chat/completions

二、使用 Serverless 函数代理 API 请求

因为是静态网站无后端服务器的场景,所以选择 通过 Vercel 免费平台部署一个"无服务器函数",隐藏 API Key。

  1. 注册 Vercel :访问 Vercel 官网,用 GitHub 账号登录
  2. 新建项目 :选择"Create a New Project",导入你的 VuePress 博客仓库,修改部署配置,添加环境变量 DEEPSEEK_API_KEY
  3. 创建 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

  1. 安装依赖
sql 复制代码
pnpm add @vuepress/plugin-register-components
  1. 配置插件

在 .vuepress/config.js 中配置插件,指定组件目录:

js 复制代码
import { path } from "@vuepress/utils";

module.exports = {
  plugins: [
    [
      '@vuepress/plugin-register-components',
      {
        // 自动注册 components 目录下的所有 Vue 组件
        componentsDir: path.resolve(__dirname, './components')
      }
    ]
  ]
};
  1. 创建组件

创建 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>
  1. 使用组件,在页面中生成摘要

组件要放在 Frontmatter 之后:

yaml 复制代码
---
lang: zh-CN
title: 01 | Chrome架构:仅仅打开了1个页面,为什么有4个进程?
---
<Post></Post>

四、访问页面

发现有了显示摘要的地方,但摘要生成失败,在 Vercel 的日志中查看,发现 DeepSeek 返回错误码 402,这是账号余额不足的问题。看了看钱包,我就不浪费这个钱了,主要是为了跑通接入这个流程,这其实就相当于接入 DeepSeek 成功了。

相关推荐
烟锁池塘柳04 分钟前
技术栈的概念及其组成部分的介绍
前端·后端·web
加减法原则5 分钟前
面试题之虚拟DOM
前端
故事与他64510 分钟前
Tomato靶机攻略
android·linux·服务器·前端·网络·web安全·postcss
jtymyxmz15 分钟前
mac 苍穹外卖 前端环境配置
前端
烛阴19 分钟前
JavaScript Rest 参数:新手也能轻松掌握的进阶技巧!
前端·javascript
chenchihwen22 分钟前
ITSM统计分析:提升IT服务管理效能 实施步骤与操作说明
java·前端·数据库
陌上烟雨寒26 分钟前
es6 尚硅谷 学习
前端·学习·es6
拉不动的猪27 分钟前
刷刷题32(uniapp初级实际项目问题-1)
前端·javascript·面试
拉不动的猪28 分钟前
刷刷题33(uniapp初级实际项目问题-2)
前端·javascript·面试
han_39 分钟前
JavaScript如何实现复制图片功能?
前端·javascript