Building a Chatbot
Define a route handler for streamText in api/chat/route.ts
. If deploying on Vercel, remember to set the max duration to a value greater than 10s.
Get the incoming messages from the request body.
Call streamText
passing in your model and messages.
Return the resulting generating as a streaming response.
Import the useChat
hook from ai/react
and use it in your chat.tsx
file.
Destructure messages
and map over them to display the chat messages.
Destructure input
, handleInputChange
, and handleSubmit
from the useChat
hook. Add an input field and a form to submit messages.
Run the app and navigate to /chat
to see the chatbot in action.
Head back to your api/chat/route.ts
file and add a system prompt to change how the model responds.
Head back to the browser and ask a new question to see the new response. Notice we've completely changed the behavior of the model without changing the model itself.
Last one! Change the system prompt to anything you would like. I suggest some kind of pop culture reference.
Now ask a question like:
Notice the response is eerily similar to what Steve Jobs might say. This is the power of system prompts.
Finally, try asking about the current weather in SF.
Notice it can't respond, we can fix this with tools.