很多初学者看到"全栈开发"、"AI 集成"这些词就头皮发麻,觉得那是程序员大牛的专属技能。其实,用对工具的话,一个完全没有后端经验的前端小白,也能在2小时内搭建一个带 AI 功能的完整网站。今天我要教你的,就是这个组合:Supabase + HolySheheep AI API

Supabase 就像一个"全能后端盒子",它帮你处理数据库、用户登录、实时订阅这些事情,你不需要懂服务器怎么配置、数据库怎么优化。而 HolySheheep AI API 则是你的 AI 大脑,可以调用 GPT-4.1、Claude Sonnet、Gemini 2.5 Flash、DeepSeek V3.2 等主流模型。最关键的是,HolySheheep 的汇率是 ¥1=$1,相比官方 ¥7.3=$1 能节省超过85%的成本,而且国内直连延迟低于50ms,注册就送免费额度,微信支付宝都能充值,非常适合国内开发者。

一、Supabase 是什么?为什么它是初学者的最佳选择

想象你要开一家餐厅,传统做法是你需要自己建厨房、买冰箱、雇厨师。但 Supabase 就像一个"餐厅解决方案提供商",它把厨房设备、食材存储、厨师招聘这些麻烦事都帮你搞定了,你只需要专注于做菜本身。

Supabase 提供的核心功能:

最棒的是,Supabase 有免费版,个人项目和小团队完全够用。而且它支持 TypeScript 和 JavaScript,前端开发者学起来零门槛。

二、3分钟创建你的第一个 Supabase 项目

(图1:Supabase 官网首页,点击 "Start your project" 按钮)

打开 Supabase 官网,用 GitHub 账号登录后,点击 "New Project" 创建新项目。填写项目名称(比如 "my-ai-app"),设置一个强密码(要记住!),选择最近的区域(新加坡或日本对中国用户比较友好)。

(图2:项目创建成功后的仪表盘界面)

创建完成后,你会看到项目仪表盘。找到左侧菜单的 SQL Editor,这是我们接下来要经常用到的地方——它允许我们直接操作数据库,就像在 Excel 里操作表格一样简单。

三、创建数据库表(像操作 Excel 一样简单)

我们先创建一个"聊天消息"表,用来存储用户和 AI 的对话记录。在 SQL Editor 中执行以下 SQL:

-- 创建聊天消息表
create table chat_messages (
  id uuid default gen_random_uuid() primary key,
  user_id text not null,
  role text not null check (role in ('user', 'assistant')),
  content text not null,
  created_at timestamp with time zone default now()
);

-- 启用实时功能(当数据变化时自动通知前端)
alter publication supabase_realtime add table chat_messages;

-- 创建索引加速查询
create index idx_chat_messages_user_id on chat_messages(user_id);
create index idx_chat_messages_created_at on chat_messages(created_at);

点击 "Run" 按钮执行。执行成功后,左侧会显示绿色对勾。

(图3:SQL 执行成功的提示)

现在数据库准备好了,接下来我们去 HolySheheep 获取 AI API 密钥。

四、获取 HolySheheep AI API Key(国内开发者首选)

在开始之前,你需要先在 立即注册 HolySheheep AI。注册完成后:

  1. 登录后在左侧菜单点击 "API Keys"
  2. 点击 "Create new key" 按钮
  3. 给这个 Key 起个名字(比如 "my-supabase-app")
  4. 复制生成的 Key,格式类似:sk-holysheep-xxxxxxxxxxxx

(图4:HolySheheep API Key 创建页面)

为什么推荐 HolySheheep?作为国内开发者,我最看重这几点:

把复制的 API Key 存好,我们接下来要用到。

五、在 Supabase Edge Functions 中调用 HolySheheep AI

Edge Functions 是 Supabase 提供的一种"无服务器函数",你可以把它理解成"在云端运行的代码片段"。我们在这里调用 HolySheheep AI API。

首先安装 Supabase CLI(在终端执行):

# 安装 Supabase CLI
npm install -g supabase

登录 Supabase

supabase login

进入项目目录,初始化 Edge Functions

cd your-project-folder supabase functions new chat-with-ai

这会在 supabase/functions/chat-with-ai 目录下创建一个 TypeScript 文件。打开这个文件,编写我们的 AI 对话逻辑:

import { serve } from "https://deno.land/[email protected]/http/server.ts";
import { createClient } from "https://esm.sh/@supabase/supabase-js@2";

const HOLYSHEEP_API_KEY = Deno.env.get("HOLYSHEEP_API_KEY")!;
const HOLYSHEEP_BASE_URL = "https://api.holysheep.ai/v1";

serve(async (req) => {
  try {
    const { user_id, user_message } = await req.json();

    // 1. 创建 Supabase 客户端(用于读写数据库)
    const supabaseClient = createClient(
      Deno.env.get("SUPABASE_URL")!,
      Deno.env.get("SUPABASE_SERVICE_ROLE_KEY")!
    );

    // 2. 获取用户最近的对话历史(用于上下文理解)
    const { data: history } = await supabaseClient
      .from("chat_messages")
      .select("role, content")
      .eq("user_id", user_id)
      .order("created_at", { ascending: true })
      .limit(10);

    // 3. 构造消息格式,发送给 HolySheheep AI
    const messages = [
      { role: "system", content: "你是一个友好的AI助手,用简洁有趣的方式回答问题。" },
      ...(history || []).map(h => ({ role: h.role, content: h.content })),
      { role: "user", content: user_message }
    ];

    // 4. 调用 HolySheheep AI API(使用 GPT-4.1 模型)
    const response = await fetch(${HOLYSHEEP_BASE_URL}/chat/completions, {
      method: "POST",
      headers: {
        "Authorization": Bearer ${HOLYSHEEP_API_KEY},
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        model: "gpt-4.1",
        messages: messages,
        max_tokens: 1000,
      }),
    });

    if (!response.ok) {
      const error = await response.text();
      return new Response(JSON.stringify({ error }), { status: response.status });
    }

    const data = await response.json();
    const aiMessage = data.choices[0].message.content;

    // 5. 保存用户消息和AI回复到数据库
    await supabaseClient.from("chat_messages").insert([
      { user_id, role: "user", content: user_message },
      { user_id, role: "assistant", content: aiMessage }
    ]);

    // 6. 返回AI回复给前端
    return new Response(JSON.stringify({ reply: aiMessage }));

  } catch (error) {
    return new Response(JSON.stringify({ error: error.message }), { status: 500 });
  }
});

部署这个函数:

# 设置 API Key(安全存储,不暴露在前端代码中)
supabase secrets set HOLYSHEEP_API_KEY=sk-holysheep-xxxxxxxxxxxx

部署 Edge Function

supabase functions deploy chat-with-ai

部署成功后,你会得到一个函数 URL,类似:https://your-project.supabase.co/functions/v1/chat-with-ai

六、编写前端页面(3步完成 AI 对话界面)

现在最激动人心的部分来了——编写前端代码!我会用原生 HTML + JavaScript,没有任何框架,保证零基础也能看懂。

<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <title>我的 AI 聊天助手</title>
  <style>
    * { box-sizing: border-box; margin: 0; padding: 0; }
    body { font-family: -apple-system, sans-serif; max-width: 800px; margin: 0 auto; padding: 20px; }
    .chat-container { border: 1px solid #ddd; border-radius: 12px; height: 500px; display: flex; flex-direction: column; }
    .messages { flex: 1; overflow-y: auto; padding: 20px; }
    .message { padding: 12px 16px; border-radius: 12px; margin-bottom: 12px; max-width: 80%; }
    .user { background: #007bff; color: white; margin-left: auto; }
    .assistant { background: #f1f1f1; }
    .input-area { display: flex; padding: 16px; border-top: 1px solid #ddd; }
    input { flex: 1; padding: 12px; border: 1px solid #ddd; border-radius: 8px; font-size: 16px; }
    button { margin-left: 12px; padding: 12px 24px; background: #007bff; color: white; border: none; border-radius: 8px; cursor: pointer; font-size: 16px; }
    button:disabled { background: #ccc; }
  </style>
</head>
<body>
  <h1>🤖 AI 聊天助手</h1>
  <p>Powered by Supabase + HolySheheep AI</p>
  
  <div class="chat-container">
    <div class="messages" id="messages"></div>
    <div class="input-area">
      <input type="text" id="userInput" placeholder="输入你的问题..." onkeypress="handleKeyPress(event)">
      <button onclick="sendMessage()" id="sendBtn">发送</button>
    </div>
  </div>

  <script>
    // 替换为你的 Supabase 项目 URL 和 Edge Function URL
    const SUPABASE_URL = "https://xxxxxxxx.supabase.co";
    const FUNCTION_URL = "https://xxxxxxxx.supabase.co/functions/v1/chat-with-ai";
    
    // 模拟用户ID(实际项目中应该是登录用户的真实ID)
    const USER_ID = "user_" + Math.random().toString(36).substr(2, 9);

    async function sendMessage() {
      const input = document.getElementById("userInput");
      const message = input.value.trim();
      if (!message) return;

      // 显示用户消息
      appendMessage("user", message);
      input.value = "";
      setLoading(true);

      try {
        const response = await fetch(FUNCTION_URL, {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ user_id: USER_ID, user_message: message })
        });

        const data = await response.json();
        
        if (data.error) {
          appendMessage("assistant", "抱歉,遇到错误: " + data.error);
        } else {
          appendMessage("assistant", data.reply);
        }
      } catch (error) {
        appendMessage("assistant", "网络错误,请检查连接后重试。");
      }

      setLoading(false);
    }

    function appendMessage(role, content) {
      const container = document.getElementById("messages");
      const div = document.createElement("div");
      div.className = message ${role};
      div.textContent = content;
      container.appendChild(div);
      container.scrollTop = container.scrollHeight;
    }

    function setLoading(loading) {
      document.getElementById("sendBtn").disabled = loading;
      document.getElementById("userInput").disabled = loading;
    }

    function handleKeyPress(e) {
      if (e.key === "Enter" && !e.shiftKey) {
        e.preventDefault();
        sendMessage();
      }
    }
  </script>
</body>
</html>

把这个 HTML 文件保存为 index.html,用浏览器打开,就可以开始和 AI 聊天了!

(图5:聊天界面效果预览)

七、成本分析与优化建议

作为个人开发者,我非常在意成本。用 HolySheheep AI API + Supabase 这个组合,实测成本非常低:

我的实战经验是:日常聊天用 Gemini 2.5 Flash,一千tokens才 $0.0025,约合人民币 1 分钱;需要深度分析时切换到 GPT-4.1。这样一个月下来,普通个人项目的 AI 成本可以控制在 10 元以内。

Supabase 免费版限制:

对于初学者练手项目来说,绰绰有余。

常见报错排查

在实际开发中,我踩过不少坑,这里把最常见的3个错误和解决方案整理出来:

错误1:API Key 无效或未设置

错误信息:
{
  "error": "Invalid API key provided"
}

原因分析:
HolySheheep API Key 没有正确配置到 Supabase secrets 中,或者 Key 已经被删除/过期。

解决方案:

在终端重新设置 API Key

supabase secrets set HOLYSHEEP_API_KEY=sk-holysheep-xxxxxxxxxxxx

验证 Key 是否设置成功

supabase secrets list

错误2:Edge Function 部署后返回 404

错误信息:
{
  "error": "Function not found"
}

原因分析:
1. 函数名拼写错误
2. 函数没有在正确的项目中部署
3. 项目引用了错误的函数 URL

解决方案:

1. 列出当前项目所有 Edge Functions

supabase functions list

2. 检查函数 URL 是否与上面列表中的名称一致

URL 格式应该是:https://xxx.supabase.co/functions/v1/你的函数名

3. 如果函数名不对,重新部署

supabase functions deploy 你的正确函数名

4. 在浏览器中直接访问函数 URL,验证是否返回 JSON 响应

错误3:前端跨域(CORS)错误

错误信息:
Access to fetch at 'https://xxx.supabase.co/functions/v1/chat-with-ai' 
from origin 'http://localhost:3000' has been blocked by CORS policy

原因分析:
浏览器默认禁止从一个域名(如 localhost)请求另一个域名(如 supabase.co)的资源,除非服务器明确允许。

解决方案:

在 Edge Function 代码中添加 CORS 头部

serve(async (req) => { // 处理 OPTIONS 预检请求 if (req.method === "OPTIONS") { return new Response(null, { headers: { "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Methods": "POST, OPTIONS", "Access-Control-Allow-Headers": "Content-Type", }, }); } // ... 正常处理逻辑 ... // 在返回响应时添加 CORS 头 return new Response(JSON.stringify({ reply: aiMessage }), { headers: { "Content-Type": "application/json", "Access-Control-Allow-Origin": "*", // 生产环境建议改成具体域名 }, }); });

错误4:数据库插入失败,提示权限不足

错误信息:
{
  "error": "new row violates row-level security policy for table \"chat_messages\""
}

原因分析:
Supabase 默认启用 Row Level Security (RLS),即使在 Edge Function 中也需要正确的权限策略。

解决方案:

在 SQL Editor 中执行以下命令,允许经过认证的请求插入数据

alter table chat_messages enable row level security; create policy "允许插入消息" on chat_messages for insert to authenticated with check (true);

或者使用 service_role key(不推荐用于生产环境,仅测试用)

将 supabaseClient 的第二个参数改为 Deno.env.get("SUPABASE_SERVICE_ROLE_KEY")!

总结:你的第一个 AI 应用已经完成了

回顾一下,我们今天做了什么:

  1. 创建了 Supabase 项目和数据库表
  2. 注册了 立即注册 HolySheheep AI,获取了 API Key
  3. 编写并部署了 Supabase Edge Function,用来调用 HolySheheep AI
  4. 用纯 HTML/JavaScript 写了一个完整的聊天界面

整个过程不需要购买服务器、不需要配置 Linux、不需要学习 Docker,你只需要一个浏览器和一颗愿意动手的心。

Supabase + HolySheheep AI 这个组合的优势总结: