To create a streaming chat endpoint compatible with the Vercel AI SDK, use the aiUseChatAdapter from @upstash/rag-chat/nextjs. This adapter takes a response from ragChat.chat and a metadata object, allowing the client-side useChat hook to consume both the stream and additional context data (like retrieved Wikipedia articles).
When implementing the POST handler:
- Extract
messages and an optional namespace from the request body. - Retrieve a
sessionId from the request cookies to maintain conversation state. - Call
ragChat.chat with streaming: true. - Use the
onContextFetched callback to filter or transform the retrieved context (e.g., limiting to the top 5 results). - Construct a metadata object containing the prompt, history, and context used.
- Return the result of
aiUseChatAdapter(response, meta).
import { aiUseChatAdapter } from "@upstash/rag-chat/nextjs";
import { ragChat } from "@/lib/rag-chat";
export async function POST(request: NextRequest) {
const { messages, namespace } = await request.json();
const sessionId = request.cookies.get("sessionId")?.value;
const question = (messages as Message[]).at(-1)?.content;
const response = await ragChat.chat(question, {
streaming: true,
sessionId: sessionId,
namespace: namespace,
onContextFetched(context) {
return context.slice(0, 5);
},
topK: 50,
});
const meta = {
usedPrompt: "...",
usedHistory: response.history.map(({ role, content }) => ({ role, content })),
usedContext: response.context.map(({ metadata, data }) => ({
url: (metadata as { url?: string }).url ?? "<NO_URL>",
data,
})),
};
return aiUseChatAdapter(response, meta);
}