Learn how to generate an image with a chat prompt using the AI SDK and Next.js
When building a chatbot, you may want to allow the user to generate an image. This can be done by creating a tool that generates an image using the experimental_generateImage function from the AI SDK.
Let's create an endpoint at /api/chat that generates the assistant's response based on the conversation history. You will also define a tool called generateImage that will generate an image based on the assistant's response.
tools/generate-image.ts
import { experimental_generateImage, tool } from 'ai';import z from 'zod';export const generateImage = tool({ description: 'Generate an image', inputSchema: z.object({ prompt: z.string().describe('The prompt to generate the image from'), }), execute: async ({ prompt }) => { const { image } = await experimental_generateImage({ model: openai.imageModel('dall-e-3'), prompt, }); // in production, save this image to blob storage and return a URL return { image: image.base64, prompt }; },});
app/api/chat/route.ts
import { convertToModelMessages, type InferUITools, stepCountIs, streamText, type UIMessage,} from 'ai';import { generateImage } from '@/tools/generate-image';const tools = { generateImage,};export type ChatTools = InferUITools<typeof tools>;export async function POST(request: Request) { const { messages }: { messages: UIMessage[] } = await request.json(); const result = streamText({ model: 'openai/gpt-4o', messages: convertToModelMessages(messages), stopWhen: stepCountIs(5), tools, }); return result.toUIMessageStreamResponse();}
In production, you should save the generated image to a blob storage and
return a URL instead of the base64 image data. If you don't, the base64 image
data will be sent to the model which may cause the generation to fail.
Let's create a simple chat interface with useChat. You will call the /api/chat endpoint to generate the assistant's response. If the assistant's response contains a generateImage tool invocation, you will display the tool result (the image in base64 format and the prompt) using the Next Image component.