Creating the API Route
In Next.js, you can create custom request handlers for a given route using Route Handlers. Route Handlers are defined in aroute.ts file and can export HTTP methods like GET, POST, PUT, PATCH, etc.
How the API route works
Declare the POST Function
Export an asynchronous function called
POST that handles incoming HTTP POST requests to this route.Extract Request Data
Retrieve the messages from the request body using
await request.json() to
get the conversation history.Call AI SDK
Pass the messages to the
streamText function imported from the AI SDK, along
with the specified model configuration.Test the Basic Implementation
Start the Development Server
Run
pnpm run dev and navigate to http://localhost:3000While you now have a working agent, it isn’t doing anything special. We need
to add system instructions to refine and restrict the model’s behavior.
Adding System Prompts
Let’s add system instructions to refine and restrict the model’s behavior. In this case, you want the model to only use information it has retrieved to generate responses. Update your route handler with the following code:app/api/chat/route.ts
Test the System Prompt
Ask a Question
Head back to the browser and try to ask the model what your favorite food
is. The model should now respond exactly as you instructed above (“Sorry, I
don’t know”) given it doesn’t have any relevant information.
The system prompt ensures the AI only responds using information from tool
calls, which we haven’t implemented yet. This prepares the foundation for RAG
functionality.
Understanding the Implementation
Request Handling
Message Parsing: Extracts messages from the request body
Streaming Response
Real-time Output: Returns streaming response to the client
Model Configuration
OpenAI Integration: Uses gpt-4o model for chat responses
System Prompt
Behavior Control: Restricts AI to only use tool-based information
