generate_image
Create images from text descriptions using Fal.ai's AI models like Flux or Stable Diffusion. Specify size, quantity, and seed for customized visual content generation.
Instructions
Generate an image using Fal.ai models like Flux or Stable Diffusion
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| prompt | Yes | Text description of the image to generate | |
| model | No | Model to use (default: fal-ai/flux/schnell) | fal-ai/flux/schnell |
| image_size | No | Image size preset | landscape_4_3 |
| num_images | No | Number of images to generate (1-4) | |
| seed | No | Seed for reproducible generation |
Implementation Reference
- src/index.ts:222-284 (handler)Main handler for the generate_image tool: parses input schema, calls fal.subscribe to generate images using the specified model and parameters, optionally downloads images locally using downloadImage helper, formats a detailed text response with image URLs and local paths.case "generate_image": { const params = GenerateImageSchema.parse(args); const result = await fal.subscribe(params.model, { input: { prompt: params.prompt, image_size: params.image_size, num_images: params.num_images, ...(params.seed && { seed: params.seed }), }, logs: true, onQueueUpdate: (update: any) => { console.error(`Queue position: ${update.position || "processing"}`); }, }); // Format the response nicely const images = (result as any).images || []; let responseText = `ā Generated ${images.length} image(s) successfully!\n\n`; // Download images locally if requested const downloadedPaths: string[] = []; const shouldDownload = params.download_images !== false; for (let idx = 0; idx < images.length; idx++) { const img = images[idx]; responseText += `Image ${idx + 1}:\n`; if (shouldDownload) { try { const localPath = await downloadImage(img.url); downloadedPaths.push(localPath); responseText += `š Saved to: ${localPath}\n`; } catch (error: any) { responseText += `ā ļø Download failed: ${error.message}\n`; } } responseText += `š URL: ${img.url}\n`; if (img.width && img.height) { responseText += `š Size: ${img.width}x${img.height}\n`; } responseText += `\n`; } if ((result as any).seed) { responseText += `š² Seed: ${(result as any).seed}\n`; } if (downloadedPaths.length > 0) { responseText += `\nš Images saved to: ${path.join(process.cwd(), "fal-images")}/\n`; } else if (shouldDownload && images.length > 0) { responseText += `\nš” Tip: Images URLs are temporary. Save them soon if needed.\n`; } return { content: [ { type: "text", text: responseText, }, ], }; }
- src/index.ts:62-69 (schema)Zod schema defining input parameters for generate_image tool, used for validation in the handler.const GenerateImageSchema = z.object({ prompt: z.string().describe("Text description of the image to generate"), model: z.string().default("fal-ai/flux/schnell").describe("Model to use for generation"), image_size: z.enum(["square", "landscape_4_3", "portrait_3_4"]).default("landscape_4_3").optional(), num_images: z.number().min(1).max(4).default(1).optional(), seed: z.number().optional(), download_images: z.boolean().default(true).optional().describe("Whether to download images locally"), });
- src/index.ts:104-137 (registration)Tool registration in the ListToolsRequestHandler response, defining name, description, and JSON inputSchema matching the Zod schema.{ name: "generate_image", description: "Generate an image using Fal.ai models like Flux or Stable Diffusion", inputSchema: { type: "object", properties: { prompt: { type: "string", description: "Text description of the image to generate", }, model: { type: "string", description: "Model to use (default: fal-ai/flux/schnell)", default: "fal-ai/flux/schnell", }, image_size: { type: "string", enum: ["square", "landscape_4_3", "portrait_3_4"], description: "Image size preset", default: "landscape_4_3", }, num_images: { type: "number", description: "Number of images to generate (1-4)", default: 1, }, seed: { type: "number", description: "Seed for reproducible generation", }, }, required: ["prompt"], }, },
- src/index.ts:19-51 (helper)Helper function to download generated image from URL to local fal-images directory, used optionally in the generate_image handler.async function downloadImage(url: string, outputDir: string = process.cwd()): Promise<string> { try { // Create images directory if it doesn't exist const imagesDir = path.join(outputDir, "fal-images"); if (!fs.existsSync(imagesDir)) { fs.mkdirSync(imagesDir, { recursive: true }); } // Generate filename from URL or timestamp const urlParts = url.split("/"); const originalName = urlParts[urlParts.length - 1]; const timestamp = new Date().getTime(); const filename = `${timestamp}-${originalName}`; const filepath = path.join(imagesDir, filename); // Download the image using buffer approach const response = await fetch(url); if (!response.ok) throw new Error(`Failed to download: ${response.statusText}`); const buffer = await response.buffer(); fs.writeFileSync(filepath, buffer); // Verify the file was created if (!fs.existsSync(filepath)) { throw new Error("File was not created successfully"); } return filepath; } catch (error) { console.error(`Failed to download image: ${error}`); throw error; } }