Create an API Route
Build the backend API endpoint for streaming chat responses
Create an API Route
Create a route handler, app/api/chat+api.ts and add the following code:
import { streamText, UIMessage, convertToModelMessages } from 'ai';
__PROVIDER_IMPORT__;
export async function POST(req: Request) {
const { messages }: { messages: UIMessage[] } = await req.json();
const result = streamText({
model: __MODEL__,
messages: await convertToModelMessages(messages),
});
return result.toUIMessageStreamResponse({
headers: {
'Content-Type': 'application/octet-stream',
'Content-Encoding': 'none',
},
});
}Let's take a look at what is happening in this code:
- Define an asynchronous
POSTrequest handler and extractmessagesfrom the body of the request. Themessagesvariable contains a history of the conversation between you and the chatbot and provides the chatbot with the necessary context to make the next generation. - Call
streamText, which is imported from theaipackage. This function accepts a configuration object that contains amodelprovider (imported fromai) andmessages(defined in step 1). You can pass additional settings to further customise the model's behaviour. - The
streamTextfunction returns aStreamTextResult. This result object contains thetoUIMessageStreamResponsefunction which converts the result to a streamed response object. - Finally, return the result to the client to stream the response.
This API route creates a POST request endpoint at /api/chat.