> ## Content Index
> Fetch the complete content index at: https://www.hubwiz.com/blog/llms.txt
> Use this file to discover other available public pages before exploring further.

# 用Vercel AI SDK构建聊天机器人
- URL: https://www.hubwiz.com/blog/build-chatbot-with-vercel-ai-sdk/
- Published: 2025-04-11T03:30:36.000Z
- Updated: 2025-04-11T03:30:36.000Z
- Description: 在这篇指南中，我们将使用 Vercel AI SDK、用于工具的 Agentic 适配器 和用于无服务器执行的 Supabase Edge Functions 来创建这样一个聊天机器人。
- Author: admin
- Tags: LIBRARY, VERCEL AI SDK, #Import 2026-10-14 14:41

想象一下构建一个能够实时响应、获取实时数据（如天气更新）并且轻松扩展的聊天机器人，同时保持低成本。

在这篇指南中，我们将使用 **Vercel AI SDK**、用于工具的 **Agentic 适配器** 和用于无服务器执行的 **Supabase Edge Functions** 来创建这样一个聊天机器人。由于 Supabase 的按调用计费模式和全球边缘部署，这种设置既强大又高效且经济实惠。

## 1、为什么选择这个技术栈？

以下是为什么这个组合是构建 AI 驱动应用程序的理想选择的原因：

- **Vercel AI SDK**：一个 TypeScript 工具包，简化了 AI 集成，具有文本生成、工具调用和流式响应等功能。它在各种框架和运行时中都非常通用。
- **Agentic 适配器**：通过实用工具（如 WeatherClient）扩展了 Vercel AI SDK，使您的聊天机器人能够根据用户查询获取实时世界数据。
- **Supabase Edge Functions**：运行在 Deno 上的无服务器函数，全球部署以实现低延迟。它们按调用次数计费（每月有 500,000 次免费调用），而不是闲置时间，因此非常经济实惠。
- **后台处理**：使用 EdgeRuntime.waitUntil 处理任务（如异步保存聊天历史记录），保持聊天机器人响应迅速。

## 2、你需要什么

开始之前，请准备好以下先决条件：

1. **Vercel AI SDK** —— 用于 AI 功能 ([文档](https://sdk.vercel.ai/docs?ref=hubwiz.com))。
2. **Agentic 适配器** —— 添加工具（如天气查询）(@agentic/ai-sdk)。
3. **Supabase Edge Functions** —— 用于在 Deno 上的无服务器执行。
4. **Supabase 数据库** —— 用于存储聊天历史记录。
5. **OpenAI API 密钥** —— 提供语言模型 ([openai.com](https://openai.com/?ref=hubwiz.com))。
6. **天气 API 密钥** —— 用于天气查询 ([weatherapi.com](https://www.weatherapi.com/?ref=hubwiz.com))。
7. **前端（可选）** —— 一个 Next.js 界面与机器人交互。

## 3、设置你的 Supabase 项目

初始化一个 Supabase 项目并在其中创建一个聊天历史记录表。

运行以下命令：

```
supabase init  
supabase login  
supabase link --project-ref <your-project-ref>

```

在你的 Supabase 数据库中创建一个 chat\_history 表：

```
create table chat_history (  
  id uuid default uuid_generate_v4() primary key,  
  user_id text,  
  message text,  
  response text,  
  created_at timestamp default now()  
);

```

该表将存储每次聊天互动。

## 4、创建一个 Supabase Edge 函数

生成一个新的 Edge 函数名为“chatbot”：

```
supabase functions new chatbot

```

这会创建 supabase/functions/chatbot/index.ts，我们将在其中添加逻辑。

## 5、编写聊天机器人逻辑

Supabase Edge 函数在 Deno 上运行，因此我们将使用 Deno 兼容的导入方式。打开 supabase/functions/chatbot/index.ts 并添加以下内容：

```
import { serve } from "https://deno.land/std@0.168.0/http/server.ts";  
import { streamText } from "https://esm.sh/ai@3.4.18";  
import { openai } from "https://esm.sh/@ai-sdk/openai@0.0.68";  
import { createAISDKTools } from "https://esm.sh/@agentic/ai-sdk@0.0.54";  
import { WeatherClient } from "https://esm.sh/@agentic/weather@0.0.23";  
import { createClient } from "https://esm.sh/@supabase/supabase-js@2.45.6";  
  
const supabase = createClient(  
  Deno.env.get("SUPABASE_URL")!,  
  Deno.env.get("SUPABASE_ANON_KEY")!  
);  
  
const weather = new WeatherClient({  
  apiKey: Deno.env.get("WEATHER_API_KEY")!,  
});  
serve(async (req) => {  
  if (req.method !== "POST") {  
    return new Response("Method not allowed", { status: 405 });  
  }  
  const { message, userId } = await req.json();  
  const { textStream } = await streamText({  
    model: openai("gpt-4o-mini"),  
    prompt: message,  
    tools: createAISDKTools(weather),  
    toolChoice: "auto",  
    temperature: 0,  
    system: "You are a helpful assistant. Be concise.",  
  });  
  // 在后台保存聊天历史  
  EdgeRuntime.waitUntil(  
    (async () => {  
      let fullResponse = "";  
      for await (const chunk of textStream) {  
        fullResponse += chunk;  
      }  
      await supabase.from("chat_history").insert({  
        user_id: userId,  
        message,  
        response: fullResponse,  
      });  
    })()  
  );  
  return new Response(textStream, {  
    headers: { "Content-Type": "text/plain" },  
  });  
});

```

**关键功能：**

- **Deno 导入**：使用基于 URL 的导入以确保 Deno 兼容性。
- **流式传输**：streamText 提供实时响应。
- **工具**：WeatherClient 在需要时获取天气数据。
- **后台任务**：EdgeRuntime.waitUntil 在不阻塞用户的情况下保存历史记录。

## 6、设置环境变量

在 supabase/functions/chatbot 中创建一个 .env.local 文件：

```
SUPABASE_URL=<your-supabase-url>  
SUPABASE_ANON_KEY=<your-supabase-anon-key>  
OPENAI_API_KEY=<your-openai-api-key>  
WEATHER_API_KEY=<your-weatherapi.com-key>

```

部署这些密钥：

```
supabase secrets set --env-file ./supabase/functions/chatbot/.env.local

```

## 7、部署 Edge 函数

本地测试：

```
supabase functions serve chatbot --env-file ./supabase/functions/chatbot/.env.local

```

部署到 Supabase：

```
supabase functions deploy chatbot

```

现在你的聊天机器人已经在全球范围内上线！

## 8、添加前端（可选）

为了一个简单的界面，可以使用 Next.js。在 pages/index.tsx 中：

```
import { useState } from "react";  
import { createClient } from "@supabase/supabase-js";  
  
const supabase = createClient(process.env.NEXT_PUBLIC_SUPABASE_URL!, process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!);  
export default function Chatbot() {  
  const [message, setMessage] = useState("");  
  const [response, setResponse] = useState("");  
  const handleSubmit = async (e) => {  
    e.preventDefault();  
    const { data: { user } } = await supabase.auth.getUser();  
    const res = await fetch("https://<your-project-ref>.supabase.co/functions/v1/chatbot", {  
      method: "POST",  
      headers: { "Content-Type": "application/json" },  
      body: JSON.stringify({ message, userId: user?.id }),  
    });  
    const reader = res.body?.getReader();  
    const decoder = new TextDecoder();  
    setResponse("");  
    while (true) {  
      const { done, value } = await reader.read();  
      if (done) break;  
      setResponse((prev) => prev + decoder.decode(value));  
    }  
  };  
  return (  
    <form onSubmit={handleSubmit}>  
      <input value={message} onChange={(e) => setMessage(e.target.value)} />  
      <button type="submit">发送</button>  
      <p>{response}</p>  
    </form>  
  );  
}

```

这提供了一个基本的界面来发送消息并查看响应。

## 9、进行测试

使用天气查询进行测试：

```
curl -X POST https://<your-project-ref>.supabase.co/functions/v1/chatbot -H "Content-Type: application/json" -d '{"message": "What is the weather in San Francisco?", "userId": "test-user"}'

```

期望的响应类似于：“San Francisco 的天气是 62°F 和晴朗。”

为什么这种方法有效

- **成本效益高**：Supabase 每月提供 500,000 次免费调用。
- **实时**：通过 streamText 实现流式响应。
- **高效**：后台任务不会阻塞用户。
- **可扩展**：全球边缘部署确保低延迟。

## 10、结束语

你已经使用 Vercel AI SDK、Agentic 工具和 Supabase Edge Functions 构建了一个现代的 AI 驱动的聊天机器人。它功能强大、价格实惠且准备就绪以扩展。根据需要添加更多工具或增强界面——祝编码愉快！

---

原文链接：[Build an AI-Powered Chatbot with Vercel AI SDK and Supabase Edge Functions](https://mitek99.medium.com/build-an-ai-powered-chatbot-with-vercel-ai-sdk-and-supabase-edge-functions-4cd051eac9ec?ref=hubwiz.com)

汇智网翻译整理，转载请标明出处