翻篇收录说明
翻篇网页快照

Chatbot Message Persistence | AI SDK

https://ai-sdk.dev/docs/ai-sdk-ui/chatbot-message-persistence

最近抓取:2026-12-04 03:03:44(北京时间)

最近内容变化:2026-11-30 23:41:35(北京时间)

这是最近一次有效抓取的文本快照,不含网页脚本、图片和动态交互内容。实际网页可能已更新。

访问原网页

页面简介

Learn how to store and load chat messages in a chatbot.

正文摘录

AI SDK UIMenuChatbot Message PersistenceCopy for LLMView MarkdownAsk AI about this pageBeing able to store and load chat messages is crucial for most AI chatbots. In this guide, we'll show how to implement message persistence with useChat and streamText. This guide does not cover authorization, error handling, or other real-world considerations. It is intended to be a simple example of how to implement message persistence. Starting a new chat When the user navigates to the chat page without providing a chat ID, we need to create a new chat and redirect to the chat page with the new chat ID. app/chat/page.tsximport { redirect } from 'next/navigation'; import { createChat } from '@util/chat-store'; export default async function Page() { const id = await createChat(); // create a new chat redirect(`/chat/${id}`); // redirect to chat page, see below } Our example chat store implementation uses files to store the chat messages. In a real-world application, you would use a database or a cloud storage service, and get the chat ID from the database. That being said, the function interfaces are designed to be easily replaced with other implementations. util/chat-store.tsimport { generateId } from 'ai'; import { existsSync, mkdirSync } from 'fs'; import { writeFile } from 'fs/promises'; import path from 'path'; // Treat chat IDs as opaque tokens before using them in file paths. const chatIdRegex = /^[A-Za-z0-9_-]+$/; export async function createChat(): Promise<string> { const id = generateId(); // generate a unique chat ID await writeFile(getChatFile(id), '[]'); // create an empty chat file return id; } function getChatFile(id: string): string { if (!chatIdRegex.test(id)) { throw new Error('Invalid chat ID'); } const chatDir = path.resolve(process.cwd(), '.chats'); const chatFile = path.resolve(chatDir, `${id}.json`); // Defense in depth: keep the resolved file inside the chat directory. if (!chatFile.startsWith(`${chatDir}${path.sep}`)) { throw new Error('Invalid chat ID'); } if (!existsSync(chatDir)) mkdirSync(chatDir, { recursive: true }); return chatFile; } The chat ID can come from the URL or the request body, so validate it as an opaque token before using it in a file path. The resolved path check ensures the file stays inside the intended .chats directory. Loading an existing chat When the user navigates to the chat page with a chat ID, we need to load the chat messages from storage. The loadChat function in our file-based chat store is implemented as follows: util/chat-store.tsimport { UIMessage } from 'ai'; import { readFile } from 'fs/promises'; export async function loadChat(id: string): Promise<UIMessage[]> { return JSON.parse(await readFile(getChatFile(id), 'utf8')); } // ... rest of the file Validating messages on the server When processing messages on the server that contain tool calls, custom metadata, or data parts, you should validate them using validateUIMessages before sending them to the model. Persisting streaming tool input An input-streaming tool part includes rawInput while tool arguments are still arriving. Persist the complete UI message, including this field, so a resumed stream can append later tool-input deltas to the exact text received before the interruption. AI SDK updates rawInput as each delta arrives and removes it when the tool input becomes available. Migrating deprecated tool rawInput Older persisted tool parts in the output-error state may contain rawInput. This field is deprecated and will be removed in the next major version. Store tool arguments in input instead. AI SDK emits a deprecation warning when validateUIMessages, safeValidateUIMessages, or convertToModelMessages encounters a defined rawInput value. UI stream processing also warns when it reconstructs a static output-error part with rawInput. Migrate each legacy part by copying rawInput to input when input is null or undefined, then remove rawInput. This preserves the current backward-compatible conversion behavior: import { isToolUIPart } from 'ai'; const migratedParts = message.parts.map(part => { if ( !isToolUIPart(part) || part.state !== 'output-error' || !('rawInput' in part) || part.rawInput === undefined ) { return part; } const { rawInput, ...partWithoutRawInput } = part; return { ...partWithoutRawInput, input: part.input ?? rawInput, }; }); Validation with tools When your messages include tool calls, validate them against your tool definitions: app/api/chat/route.tsimport { convertToModelMessages, createUIMessageStreamResponse, streamText, toUIMessageStream, UIMessage, validateUIMessages, tool, } from 'ai'; import { z } from 'zod'; import { loadChat, saveChat } from '@util/chat-store'; import { dataSchemas, metadataSchema } from '@util/schemas'; // Define your tools const tools = { weather: tool({ description: 'Get weather information', inputSchema: z.object({ location: z.string(), units: z.enum(['celsius', 'fahrenheit']), }), execute: async ({ location, units }) => { /* tool implementation */ }, }), // other tools }; export async function POST(req: Request) { const { message, id } = await req.json(); // Load previous messages from database const previousMessages = await loadChat(id); // Append new message to previousMessages messages const messages = [...previousMessages, message]; // Validate loaded messages against // tools, data parts schema, and metadata schema const validatedMessages = await validateUIMessages({ messages, tools, // Ensures tool calls in messages match current schemas dataSchemas, metadataSchema, }); const result = streamText({ model: 'openai/gpt-6-luna', messages: await convertToModelMessages(validatedMessages), tools, }); return createUIMessageStreamResponse({ stream: toUIMessageStream({ stream: result.stream, originalMessages: messages, onEnd: ({ messages }) => { saveChat({ chatId: id, messages }); }, }), }); } Handling validation errors Handle validation errors gracefully when messages from the database don't match current schemas: app/api/chat/route.tsimport { convertToModelMessages, streamText, validateUIMessages, TypeValidationError, } from 'ai'; import { type MyUIMessage } from '@/types'; export async function POST(req: Request) { const { message, id } = await req.json(); // Load and validate messages from database let validatedMessages: MyUIMessage[]; try { const previousMessages = await loadMessagesFromDB(id); validatedMessages = await validateUIMessages({ // append the new message to the previous messages: messages: [...previousMessages, message], tools, metadataSchema, }); } catch (error) { if (error instanceof TypeValidationError) { // Log validation error for monitoring console.error('Database messages validation failed:', error); // Could implement message migration or filtering here // For now, start with empty history validatedMessages = []; } else { throw error; } } // Continue with validated messages... } Displaying the chat Once messages are loaded from storage, you can display them in your chat UI. Here's how to set up the page component and the chat display: app/chat/[id]/page.tsximport { loadChat } from '@util/chat-store'; import Chat from '@ui/chat'; export default async function Page(props: { params: Promise<{ id: string }> }) { const { id } = await props.params; const messages = await loadChat(id); return <Chat id={id} initialMessages={messages} />; } The chat component uses the useChat hook to manage the conversation: ui/chat.tsx'use client'; import { UIMessage, useChat } from '@ai-sdk/react'; import { DefaultChatTransport } from 'ai'; import { useState } from 'react'; export default function Chat({ id, initialMessages, }: { id?: string | undefined; initialMessages?: UIMessage[] } = {}) { const [input, setInput] = useState(''); const { sendMessage, messages } = useChat({ id, // use the provided chat ID messages: initialMessages, // load initial messages transport: new DefaultChatTransport({ api: '/api/chat', }), }); const handleSubmit = (e: React.FormEvent) => { e.preventDefault(); if (input.trim()) { sendMessage({ text: input }); setInput(''); } }; // simplified rendering code, extend as needed: return ( <div> {messages.map(m => ( <div key={m.id}> {m.role === 'user' ? 'User: ' : 'AI: '} {m.parts .map(part => (part.type === 'text' ? part.text : '')) .join('')} </div> ))} <form onSubmit={handleSubmit}> <input value={input} onChange={e => setInput(e.target.value)} placeholder="Type a message..." /> <button type="submit">Send</button> </form> </div> ); } Storing messages useChat sends the chat id and the messages to the backend. The useChat message format is different from the ModelMessage format. The useChat message format is designed for frontend display, and contains additional fields such as id and createdAt. We recommend storing the messages in the useChat message format.When loading messages from storage that contain tools, metadata, or custom data parts, validate them using validateUIMessages before processing (see the validation section above). Storing messages is done in the onEnd callback of the toUIMessageStream function. onEnd receives the complete messages including the new AI response as UIMessage[]. app/api/chat/route.tsimport { openai } from '@ai-sdk/openai'; import { saveChat } from '@util/chat-store'; import { convertToModelMessages, createUIMessageStreamResponse, streamText, toUIMessageStream, UIMessage, } from 'ai'; export async function POST(req: Request) { const { messages, chatId }: { messages: UIMessage[]; chatId: string } = await req.json(); const result = streamText({ model: 'openai/gpt-6-luna', messages: await convertToModelMessages(messages), }); return createUIMessageStreamResponse({ stream: toUIMessageStream({ stream: result.stream, originalMessages: messages, onEnd: ({ messages }) => { saveChat({ chatId, messages }); }, }), }); } The actual storage of the messages is done in the saveChat function, which in our file-based chat store is implemented as follows: util/chat-store.tsimport { UIMessage } from 'ai'; import { writeFile } from