本文将手把手教你搭建一个:

  • ✅ 带前端聊天界面
  • ✅ AI 流式返回
  • ✅ 自动存储聊天记录到数据库
  • ✅ 可部署上线的完整 AI Web 应用

效果类似一个简化版 ChatGPT。

选型对比

需求 选型
做 AI 聊天界面 / Next.js 项目 Vercel AI SDK ✅ (本文选用)
做复杂 Agent / RAG / 多步编排 LangChain.js
只调 OpenAI 一家、追求极简 OpenAI SDK

项目结构

ai-chat-app/
├── app/
│   ├── api/
│   │   └── chat/
│   │       └── route.ts
│   ├── layout.tsx
│   ├── page.tsx
│   └── globals.css
├── lib/supabase.ts
├── package.json
├── tsconfig.json
├── next.config.js
├── postcss.config.js
├── tailwind.config.js
└── .env.local

一、技术栈

  • Next.js (App Router)
  • Vercel AI SDK
  • OpenAI
  • Supabase(存储聊天记录)
  • Tailwind CSS

数据库用的是 Supabase,部署推荐 Vercel。

二、项目初始化

npx create-next-app ai-chat-db
cd ai-chat-db
npm install ai @ai-sdk/openai @supabase/supabase-js
npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p

三、创建 Supabase 表

在 Supabase 控制台执行 SQL:

根据自己的需求增减字段

create table messages (
  id uuid default gen_random_uuid() primary key,
  role text not null,
  content text not null,
  created_at timestamp default now()
);

四、环境变量配置

# .env.local

OPENAI_API_KEY=sk-xxxx
SUPABASE_URL=https://xxxx.supabase.co
SUPABASE_SERVICE_ROLE_KEY=xxxxx

五、Supabase 客户端封装

// lib/supabase.ts

import { createClient } from "@supabase/supabase-js";

export const supabase = createClient(
  process.env.SUPABASE_URL!,
  process.env.SUPABASE_SERVICE_ROLE_KEY!
);

六、后端 API(AI + 数据库存储)

// app/api/chat/route.ts

import { openai } from "@ai-sdk/openai";
import { streamText } from "ai";
import { supabase } from "@/lib/supabase";

export const runtime = "edge";

export async function POST(req: Request) {
  const { messages } = await req.json();

  // 保存用户消息
  const userMessage = messages[messages.length - 1];
  await supabase.from("messages").insert({
    role: "user",
    content: userMessage.content
  });

  const result = await streamText({
    model: openai("gpt-4o-mini"),
    messages,
    system: "你是一个耐心、专业的中文 AI 助手"
  });

  const stream = result.toDataStreamResponse();

  // 监听流结束后保存 AI 回复
  result.onFinish(async (final) => {
    await supabase.from("messages").insert({
      role: "assistant",
      content: final.text
    });
  });

  return stream;
}

七、前端聊天页面

// app/page.tsx

"use client";

import { useChat } from "ai/react";

export default function Home() {
  const {
    messages,
    input,
    handleInputChange,
    handleSubmit,
    isLoading
  } = useChat({
    api: "/api/chat"
  });

  return (
    <div className="flex flex-col h-screen max-w-2xl mx-auto p-4">
      <h1 className="text-2xl font-bold mb-4">🤖 AI 聊天助手</h1>

      <div className="flex-1 overflow-y-auto space-y-3 mb-4">
        {messages.map((m) => (
          <div
            key={m.id}
            className={`p-3 rounded ${
              m.role === "user"
                ? "bg-blue-200 text-right"
                : "bg-gray-100 text-left"
            }`}
          >
            <b>{m.role === "user" ? "我" : "AI"}</b>
            {m.content}
          </div>
        ))}

        {isLoading && <div>AI 正在思考中...</div>}
      </div>

      <form onSubmit={handleSubmit} className="flex gap-2">
        <input
          value={input}
          onChange={handleInputChange}
          placeholder="请输入你的问题..."
          className="flex-1 border px-3 py-2 rounded"
        />
        <button
          disabled={isLoading}
          className="bg-blue-500 text-white px-4 rounded"
        >
          发送
        </button>
      </form>
    </div>
  );
}

八、globals.css + layout.tsx

/* globals.css */
@tailwind base;
@tailwind components;
@tailwind utilities;

body {
  background: #f5f5f5;
}
/* app/layout.tsx */
import "./globals.css";

export const metadata = {
  title: "AI Chat App",
  description: "Vercel AI SDK Demo"
};

export default function RootLayout({
  children
}: {
  children: React.ReactNode;
}) {
  return (
    <html lang="zh">
      <body>{children}</body>
    </html>
  );
}

npm run dev 运行项目,即可看到:

✅ AI 聊天
✅ 流式输出
✅ 聊天记录自动存入数据库

数据库效果

role content
user 什么是 React
assistant React 是一个前端 UI 库…

九、部署到 Vercel

具体细节可以参考我之前的文章【前端】使用Vercel部署前端项目,api转发到后端服务器

npm i -g vercel
vercel

在 Vercel 配置环境变量:

OPENAI_API_KEY
SUPABASE_URL
SUPABASE_SERVICE_ROLE_KEY

即可上线。

十、总结

本文实现了一个:
前端:Next.js 聊天界面
后端:Vercel AI SDK + OpenAI
数据库:Supabase 存储聊天记录

你已经拥有一个完整的:
✅ AI Web 应用
✅ 带持久化存储
✅ 可二次开发

可扩展方向

  • 会话分组(conversation_id)
  • 用户登录系统
  • Markdown 渲染
  • 向量数据库(RAG)
  • 多模型切换
Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐