Backend

Open the file at the following location: app/api/chat/route.ts.

You should see the following code which defines a POST request at the /api/chat endpoint.

app/api/chat/route.ts
export async function POST(request: Request) {}

Pull in the messages from the request body.

app/api/chat/route.ts
export async function POST(request: Request) {
  const { messages } = await request.json(); 
}

Import and call streamText, passing in a model and the messages.

app/api/chat/route.ts
import { streamText } from "ai"; 
import { openai } from "@ai-sdk/openai"; 

export async function POST(request: Request) {
  const { messages } = await request.json();
  const result = await streamText({ 
    model: openai("gpt-4o"), 
    messages, 
  }); 
}

Return the model's response using the toAIStreamResponse helper method on result.

app/api/chat/route.ts
import { streamText } from "ai";
import { openai } from "@ai-sdk/openai";

export async function POST(request: Request) {
  const { messages } = await request.json();
  const result = await streamText({
    model: openai("gpt-4o"),
    system: "You are a helpful assistant.",
    messages,
  });
  return result.toAIStreamResponse(); 
}