The ai-sdk package provides a convenient way to generate text using AI models. To create a streaming response that can be used in a server, you can utilize the streamText.toDataStreamResponse() method or directly create a Response object. Below are examples that demonstrate how to use generateText from the ai-sdk package with streamText.toDataStreamResponse() and Response, avoiding the deprecated StreamingTextResponse.
Prerequisites
Ensure you have the ai-sdk package installed. If not, you can install it using npm or yarn:
npm install ai-sdk
# or
yarn add ai-sdk
Example 1: Using streamText.toDataStreamResponse()
This example shows how to generate text using generateText and return a response using streamText.toDataStreamResponse().
import { generateText, streamText } from 'ai-sdk';
const text = await generateText({
// Your model or prompt configuration here
model: 'your-model-name',
prompt: 'Tell me a joke.',
});
const { readable, toDataStreamResponse } = streamText(text);
const response = toDataStreamResponse(readable);
// Use response in your server framework, e.g., Next.js, Express
// For example, in Next.js:
export async function GET(request) {
return new Response(readable, {
headers: {
'Content-Type': 'text/plain; charset=utf-8',
},
});
}
However, the above example still needs adjustment for direct usage. A more accurate approach would directly utilize streamText with a model and prompt:
import { streamText } from 'ai-sdk';
export async function GET(request) {
const { readable } = await streamText({
model: 'your-model-name',
prompt: 'Tell me a joke.',
});
return new Response(readable, {
headers: {
'Content-Type': 'text/plain; charset=utf-8',
},
});
}
Example 2: Directly Using Response
This example directly creates a Response object with the generated text stream.
import { streamText } from 'ai-sdk';
export async function POST(request) {
const { readable } = await streamText({
model: 'your-model-name',
prompt: 'Tell me a joke.',
});
return new Response(readable, {
headers: {
'Content-Type': 'text/plain; charset=utf-8',
},
});
}
Example 3: Using streamText.toDataStreamResponse() Correctly
If you specifically need to use toDataStreamResponse, ensure you're handling it as part of a server response:
import { streamText } from 'ai-sdk';
export async function GET(request) {
const { readable, toDataStreamResponse } = await streamText({
model: 'your-model-name',
prompt: 'Tell me a joke.',
});
const response = toDataStreamResponse(readable);
// Handle response according to your server framework
return response;
}
Note
The examples provided assume you're working within a server environment like Next.js or a similar framework that supports Response objects directly. Adjustments might be necessary based on your specific use case and server setup.
Always refer to the latest ai-sdk documentation and your server framework's documentation for the most up-to-date practices and compatibility information.