Streaming UI Advanced
Streaming UI goes beyond text streaming — it lets the AI generate entire React components that render progressively as the response arrives. This creates rich, interactive experiences where the UI itself is AI-generated.
Generative UI with streamUI
The streamUI function lets you render React components on the server and stream them to the client:
TypeScript - app/actions.tsx
'use server'; import { streamUI } from 'ai/rsc'; import { openai } from '@ai-sdk/openai'; import { z } from 'zod'; export async function streamComponent(prompt: string) { const result = await streamUI({ model: openai('gpt-4o'), prompt, text: ({ content }) => <p>{content}</p>, tools: { weather: { description: 'Get the weather for a location', parameters: z.object({ location: z.string(), }), generate: async function* ({ location }) { yield <div>Loading weather for {location}...</div>; const weather = await getWeather(location); return <WeatherCard data={weather} />; }, }, }, }); return result.value; }
Edge Runtime for Streaming
Deploy streaming endpoints to the Edge Runtime for lower latency:
TypeScript - app/api/chat/route.ts
import { openai } from '@ai-sdk/openai'; import { streamText } from 'ai'; // Deploy this route handler to the edge export const runtime = 'edge'; export async function POST(req: Request) { const { messages } = await req.json(); const result = await streamText({ model: openai('gpt-4o'), messages, }); return result.toDataStreamResponse(); }
Progressive Loading with Suspense
Combine React Suspense with AI streaming for progressive loading experiences:
TypeScript
import { Suspense } from 'react'; async function AIInsight({ data }: { data: string }) { const { text } = await generateText({ model: openai('gpt-4o'), prompt: `Analyze this data: ${data}`, }); return <div>{text}</div>; } export default function Dashboard() { return ( <div> <h1>Dashboard</h1> <Suspense fallback={<div>Generating AI insight...</div>}> <AIInsight data="quarterly sales data" /> </Suspense> </div> ); }
Edge vs Node: Use the Edge Runtime when you need low-latency streaming and your AI provider supports it. Use the Node.js runtime when you need access to Node APIs, databases, or file system operations during AI processing.
Streaming UI Complete!
You now know how to build advanced streaming interfaces. In the final lesson, learn production best practices for deploying AI apps.
Next: Best Practices →