generate_image
Generate images from text prompts using Fal.ai models including Flux and Stable Diffusion, with customizable size and output options.
Instructions
Generate an image using Fal.ai models like Flux or Stable Diffusion
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| image_size | No | Image size preset | landscape_4_3 |
| model | No | Model to use (default: fal-ai/flux/schnell) | fal-ai/flux/schnell |
| num_images | No | Number of images to generate (1-4) | |
| prompt | Yes | Text description of the image to generate | |
| seed | No | Seed for reproducible generation |
Implementation Reference
- src/index.ts:222-284 (handler)Main handler for the generate_image tool: parses input with Zod schema, calls fal.subscribe to generate images using the specified model (default flux/schnell), optionally downloads images to local fal-images directory using downloadImage helper, and returns formatted text response with URLs and 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 for validating generate_image tool inputs, used in the handler to parse args.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 ListToolsResponse, 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 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; } }