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

Next.js Pages Router | AI SDK

https://ai-sdk.dev/docs/getting-started/nextjs-pages-router

最近抓取:2026-12-02 15:25:21(北京时间)

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

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

访问原网页

页面简介

Add an agent with a streaming chat interface to an existing Next.js Pages Router application.

正文摘录

Getting StartedMenuNext.js Pages RouterCopy for LLMView MarkdownAsk AI about this pageThis guide shows how to add an agent with a streaming chat user interface to an existing Next.js Pages Router application. For new applications, we recommend the Next.js App Router quickstart. If you are unfamiliar with the concepts of Prompt Engineering and HTTP Streaming, you can optionally read these documents first. Prerequisites To follow this guide, you'll need: An existing Next.js 13+ application using the Pages Router. Node.js 22+ and pnpm installed on your local development machine. A Vercel AI Gateway API key. If you haven't obtained your Vercel AI Gateway API key, you can do so by signing up on the Vercel website. Set Up Your Application Open a terminal in the root directory of your existing Next.js Pages Router application. Install dependencies Install ai and @ai-sdk/react, the AI package and AI SDK's React hooks. The AI SDK's Vercel AI Gateway provider ships with the ai package. You'll also install zod, a schema validation library used for defining tool inputs. This guide uses the Vercel AI Gateway provider so you can access hundreds of models from different providers with one API key, but you can switch to any provider or model by installing its package. Check out available AI SDK providers for more information. pnpmnpmyarnbun$ pnpm add ai @ai-sdk/react zod Configure your AI Gateway API key Create a .env.local file in your project root and add your AI Gateway API key. This key authenticates your application with the Vercel AI Gateway. $ touch .env.local Edit the .env.local file: .env.localAI_GATEWAY_API_KEY=xxxxxxxxx Replace xxxxxxxxx with your actual Vercel AI Gateway API key. The AI SDK's Vercel AI Gateway Provider will default to using the AI_GATEWAY_API_KEY environment variable. Create a Route Handler As long as you are on Next.js 13+, you can use Route Handlers (using the App Router) alongside the Pages Router. This is recommended to enable you to use the Web APIs interface/signature and to better support streaming. Create a Route Handler (app/api/chat/route.ts) and add the following code: GatewayProviderCustomClaude Sonnet 5.5app/api/chat/route.tsimport { streamText, UIMessage, convertToModelMessages, createUIMessageStreamResponse, toUIMessageStream, } from 'ai'; export async function POST(req: Request) { const { messages }: { messages: UIMessage[] } = await req.json(); const result = streamText({ model: "anthropic/claude-sonnet-5.5", messages: await convertToModelMessages(messages), }); return createUIMessageStreamResponse({ stream: toUIMessageStream({ stream: result.stream }), }); } Let's take a look at what is happening in this code: Define an asynchronous POST request handler and extract messages from the body of the request. The messages variable contains a history of the conversation between you and the chatbot and provides the chatbot with the necessary context to make the next generation. The messages are of UIMessage type, which are designed for use in application UI - they contain the entire message history and associated metadata like timestamps. Call streamText, which is imported from the ai package. This function accepts a configuration object that contains a model provider and messages (defined in step 1). You can pass additional settings to further customize the model's behavior. The messages key expects a ModelMessage[] array. This type is different from UIMessage in that it does not include metadata, such as timestamps or sender information. To convert between these types, we use the convertToModelMessages function, which strips the UI-specific metadata and transforms the UIMessage[] array into the ModelMessage[] format that the model expects. The streamText function returns a StreamTextResult. Pass its stream to toUIMessageStream and return it with createUIMessageStreamResponse to create a streamed response object. Finally, return the result to the client to stream the response. This Route Handler creates a POST request endpoint at /api/chat. Choosing a Provider The AI SDK supports dozens of model providers through first-party, OpenAI-compatible, and community packages. This guide uses the Vercel AI Gateway provider, which is the default global provider. This means you can access models using a simple string in the model configuration: GatewayProviderCustomClaude Sonnet 5.5model: "anthropic/claude-sonnet-5.5"; You can also explicitly import and use the gateway provider in two other equivalent ways: // Option 1: Import from 'ai' package (included by default) import { gateway } from 'ai'; model: gateway('anthropic/claude-sonnet-5.5'); // Option 2: Install and import from '@ai-sdk/gateway' package import { gateway } from '@ai-sdk/gateway'; model: gateway('anthropic/claude-sonnet-5.5'); Using other providers To use a different provider, install its package and create a provider instance. For example, to use OpenAI directly: pnpmnpmyarnbun$ pnpm add @ai-sdk/openai import { openai } from '@ai-sdk/openai'; model: openai('gpt-6-astra'); Updating the global provider You can change the default global provider so string model references use your preferred provider everywhere in your application. Learn more about provider management. Pick the approach that best matches how you want to manage providers across your application. Wire up the UI Now that you have an API route that can query an LLM, it's time to set up your frontend. The AI SDK's UI package abstracts the complexity of a chat interface into one hook, useChat. Update your root page (pages/index.tsx) with the following code to show a list of chat messages and provide a user message input: pages/index.tsximport { useChat } from '@ai-sdk/react'; import { useState } from 'react'; export default function Chat() { const [input, setInput] = useState(''); const { messages, sendMessage } = useChat(); return ( <div className="flex flex-col w-full max-w-md py-24 mx-auto stretch"> {messages.map(message => ( <div key={message.id} className="whitespace-pre-wrap"> {message.role === 'user' ? 'User: ' : 'AI: '} {message.parts.map((part, i) => { switch (part.type) { case 'text': return <div key={`${message.id}-${i}`}>{part.text}</div>; } })} </div> ))} <form onSubmit={e => { e.preventDefault(); sendMessage({ text: input }); setInput(''); }} > <input className="fixed dark:bg-zinc-900 bottom-0 w-full max-w-md p-2 mb-8 border border-zinc-300 dark:border-zinc-800 rounded shadow-xl" value={input} placeholder="Say something..." onChange={e => setInput(e.currentTarget.value)} /> </form> </div> ); } This page utilizes the useChat hook, which will, by default, use the POST API route you created earlier (/api/chat). The hook provides functions and state for handling user input and form submission. The useChat hook provides multiple utility functions and state variables: messages - the current chat messages (an array of objects with id, role, and parts properties). sendMessage - a function to send a message to the chat API. The component uses local state (useState) to manage the input field value, and handles form submission by calling sendMessage with the input text and then clearing the input field. The LLM's response is accessed through the message parts array. Each message contains an ordered array of parts that represents everything the model generated in its response. These parts can include plain text, reasoning tokens, and more that you will see later. The parts array preserves the sequence of the model's outputs, allowing you to display or process each component in the order it was generated. Running Your Application With that, you have built everything you need for your chatbot! To start your application, use the command: $ pnpm run dev Head to your browser and open http://localhost:3000. You should see an input field. Test it out by entering a message and see the AI chatbot respond in real-time! The AI SDK makes it fast and easy to build AI chat interfaces with Next.js. Enhance Your Chatbot with Tools While large language models (LLMs) have incredible generation capabilities, they struggle with discrete tasks (e.g. mathematics) and interacting with the outside world (e.g. getting the weather). This is where tools come in. Tools are actions that an LLM can invoke. The results of these actions can be reported back to the LLM to be considered in the next response. For example, if a user asks about the current weather, without tools, the model would only be able to provide general information based on its training data. But with a weather tool, it can fetch and provide up-to-date, location-specific weather information. Update Your Route Handler Let's start by giving your chatbot a weather tool. Update your Route Handler (app/api/chat/route.ts): GatewayProviderCustomClaude Sonnet 5.5app/api/chat/route.tsimport { streamText, UIMessage, convertToModelMessages, tool, createUIMessageStreamResponse, toUIMessageStream, } from 'ai'; import { z } from 'zod'; export async function POST(req: Request) { const { messages }: { messages: UIMessage[] } = await req.json(); const result = streamText({ model: "anthropic/claude-sonnet-5.5", messages: await convertToModelMessages(messages), tools: { weather: tool({ description: 'Get the weather in a location (fahrenheit)', inputSchema: z.object({ location: z.string().describe('The location to get the weather for'), }), execute: async ({ location }) => { const temperature = Math.round(Math.random() * (90 - 32) + 32); return { location, temperature, }; }, }), }, }); return createUIMessageStreamResponse({ stream: toUIMessageStream({ stream: result.stream }), }); } In this updated code: You import the tool function from the ai package and z from zod for schema validation. You define a tools object with a weather tool. This tool: Has a description that helps the model understand when to use it. Defines inputSchema using a Zod schema, specifying that it requires a location string to execute this tool. The model will attempt to extract thi