跳到正文
DEV Community· belcore·· 38 分鐘前AI 評分56

Belcore 如何在 5 分鐘內為 Next.js 聊天機械人加入長期記憶

Add long-term memory to a Next.js chatbot in 5 minutes

AI 導讀

教程示範如何使用 Belcore 和 Vercel AI SDK,約 5 分鐘為 Next.js 聊天機械人加入長期記憶。對話歷史保存在自家資料庫,每輪送往 Belcore,由它挑選與當前問題相關的對話作答,並回傳供下輪使用的情緒狀態。範例以 JSON 檔案儲存對話,部署至 serverless 前需改用 Postgres、Redis 或其他儲存方式;目前只支援文字,工具呼叫和檔案部分會被丟棄。

正文

Most chatbots forget. You tell one about your peanut allergy on Monday, and on Friday it recommends a satay place.

The usual fix is to send the whole conversation on every call. That works until the history gets long: the prompt gets expensive, and models get worse at finding the one line that matters in a wall of old messages.

This tutorial adds long-term memory to a Next.js chatbot with Belcore and the Vercel AI SDK. It takes about five minutes, and you can copy the whole app.

How it works

You keep the conversation history in your database, as you probably already do. On each turn you send the full history to Belcore. Belcore picks the turns that matter for the current question and answers from them.

your DB ──history──▶ Belcore ──reply + emotion state──▶ your DB

Belcore does not store the conversation text. Your database stays the only copy. Belcore also returns a small emotion state (a few numbers) that you save and send back next turn, so the assistant's tone stays consistent.

1. Get the example

npx degit terracore-kr/belcore-integrations/examples/nextjs-chat my-chat
cd my-chat
npm install

2. Add a key

Get a key at belcore.xyz/developers/signup. Signup gives 5,000 free calls and needs no card.

cp .env.example .env.local
# paste the key into BELCORE_API_KEY

3. Run it

npm run dev

Open http://localhost:3000 and try this:

  1. "I'm allergic to peanuts and I'm planning a trip to Lisbon in May."
  2. Chat about something else for a while.
  3. "What should I watch out for when I eat out on my trip?"

Now stop the server, start it again, reload the page, and ask again. It still knows, because the history lives in a file on your machine and goes out with every call.

The code that matters

The whole chat turn is one route handler. Belcore plugs into the AI SDK as a provider, so it is a normal generateText call:

// app/api/chat/route.ts
import { generateText } from "ai"
import { belcore } from "@belcore/ai-sdk"
import { loadConversation, saveConversation } from "@/lib/store"

export async function POST(req: Request) {
  const { id, message } = await req.json()

  // 1. Load the full history from your database and add the new message.
  const conversation = await loadConversation(id)
  conversation.messages.push({ role: "user", content: message })

  // 2. Send the whole history. Belcore picks the turns that matter and answers.
  const { text, providerMetadata } = await generateText({
    model: belcore(),
    system: "You are a friendly assistant.",
    messages: conversation.messages,
    providerOptions: conversation.emotion
      ? { belcore: { emotion: conversation.emotion } }
      : undefined,
  })

  // 3. Save the reply and the new emotion state back to your database.
  conversation.messages.push({ role: "assistant", content: text })
  conversation.emotion = providerMetadata?.belcore?.emotion
  await saveConversation(id, conversation)

  return Response.json({ reply: text })
}

lib/store.ts is two functions that read and write a JSON file. Swap them for Postgres, Redis or whatever you already use before you deploy. Serverless file systems are temporary, so the JSON file will not survive there.

The response also tells you how the reply was built: providerMetadata.belcore.memory is "long-term" when Belcore searched the whole history, and "recent" when only the latest messages were used (a short conversation, or a fallback).

Not on the AI SDK?

The same call is available elsewhere:

npm install @belcore/langchain   # LangChain.js
npm install @belcore/sdk         # plain TypeScript client
npx -y @belcore/mcp              # MCP server for Claude Desktop, Cursor
pip install belcore              # Python
pip install langchain-belcore    # LangChain (Python)

Limits

  • Text only. Tool calls and file parts are dropped.
  • streamText works, but the reply arrives as one chunk.
  • Settings like temperature are ignored for now.

Source for the example and all integrations (Apache-2.0): github.com/terracore-kr/belcore-integrations

來源:DEV Community · dev.to