Here are some examples using the modern AI SDK patterns with streamText and toDataStreamResponse():
Basic Streaming Example
import { streamText } from 'ai';
import { openai } from '@ai-sdk/openai';
export async function POST(req: Request) {
const { messages } = await req.json();
const result = await streamText({
model: openai('gpt-4-turbo'),
messages,
});
return result.toDataStreamResponse();
}
With Tool Calling
import { streamText } from 'ai';
import { openai } from '@ai-sdk/openai';
import { z } from 'zod';
export async function POST(req: Request) {
const { messages } = await req.json();
const result = await streamText({
model: openai('gpt-4-turbo'),
messages,
tools: {
getWeather: {
description: 'Get the weather in a location',
parameters: z.object({
location: z.string().describe('The location to get the weather for'),
}),
execute: async ({ location }) => {
// Your weather API call here
return `It's 72°F in ${location}`;
},
},
},
});
return result.toDataStreamResponse();
}
With Custom Headers
import { streamText } from 'ai';
import { anthropic } from '@ai-sdk/anthropic';
export async function POST(req: Request) {
const { messages } = await req.json();
const result = await streamText({
model: anthropic('claude-3-opus-20240229'),
messages,
temperature: 0.7,
maxTokens: 1000,
});
return result.toDataStreamResponse({
headers: {
'X-Custom-Header': 'value',
'Cache-Control': 'no-cache',
},
});
}
Using Response Constructor
import { streamText } from 'ai';
import { openai } from '@ai-sdk/openai';
export async function POST(req: Request) {
const { messages } = await req.json();
const result = await streamText({
model: openai('gpt-4-turbo'),
messages,
});
// Convert to Response manually if you need more control
const stream = result.toDataStream();
return new Response(stream, {
headers: {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive',
},
});
}
With Error Handling
import { streamText } from 'ai';
import { openai } from '@ai-sdk/openai';
export async function POST(req: Request) {
try {
const { messages } = await req.json();
const result = await streamText({
model: openai('gpt-4-turbo'),
messages,
onFinish: ({ text, usage, finishReason }) => {
// Log usage or perform other actions
console.log('Finished streaming:', { usage, finishReason });
},
});
return result.toDataStreamResponse();
} catch (error) {
return new Response('Error processing request', { status: 500 });
}
}
With System Messages and Metadata
import { streamText } from 'ai';
import { openai } from '@ai-sdk/openai';
export async function POST(req: Request) {
const { messages, userId } = await req.json();
const result = await streamText({
model: openai('gpt-4-turbo'),
system: 'You are a helpful assistant.',
messages,
metadata: {
userId,
timestamp: new Date().toISOString(),
},
});
return result.toDataStreamResponse();
}
These examples show the current recommended approach using streamText and toDataStreamResponse(). The old StreamingTextResponse class has been deprecated in favor of these newer, more flexible APIs that provide better type safety and integration with the rest of the AI SDK.