In the previous guide, we built a streaming chat interface using the raw OpenAI API. It worked, but required a fair bit of manual work: decoding text streams, managing message state, and wiring everything together from scratch. That approach is great for learning, but in real-world projects, you often want something more ergonomic, robust, and reusable.
Thatâs where the AI SDK comes in. It abstracts away the boilerplate and gives you a clean, developer-friendly interface for building chat UIs with streaming support out of the box, on both the server and client.
Letâs start by installing the packages youâll need: one for working with OpenAI and another for the core AI SDK functionality:
This gives you access to the OpenAI model bindings as well as utility functions like streamText.
Hereâs the magic: with just a few lines of code, you can handle streaming chat completions in your API route without manually managing the stream or setting response headers:
With this, the SDK handles everything under the hood: it initiates the request, handles the stream, and returns a properly formatted text/event-stream response. No manual setup required.
To make the frontend just as elegant, weâll install the React integration package:
This gives you access to useChat , a custom hook that handles message state, user input, and streaming updates automatically.
Previously, our UI had multiple useState hooks, a custom handleSubmit function, and logic for handling the incoming stream. Hereâs how all of that can now be replaced with useChat:
With just a few lines, your component now supports full streaming chat behavior, input handling, message tracking, and real-time updates, all without the overhead of managing it yourself.
Thatâs it! With the AI SDK, weâve cut down the code dramatically, from dozens of lines across multiple files to just a few clean abstractions. Even better, we didnât lose any functionality, we gained maintainability, readability, and reusability.
This approach is great if you want to move fast, keep your codebase clean, and focus on the parts of your app that make it unique. In the next section, weâll look at ways to customize the behavior even further, like adding system prompts, handling errors, or styling the UI for production.