DEV Community

Sh Raj
Sh Raj

Posted on

How to Create an AI Image Generator Using Cloudflare Workers AI SDK

How to Create an AI Image Generator Using Cloudflare Workers AI SDK

Cloudflare Workers, with its AI SDK, offers a powerful platform to create scalable AI applications, including an AI image generator. Here’s a step-by-step guide on how to achieve this using the Stable Diffusion model, along with sample code and customization options.

Step 1: Setting Up Cloudflare Workers

First, you need to create a Cloudflare Worker. If you don't have a Cloudflare account, you can sign up at Cloudflare's website. Once you have your account, follow these steps to set up a Worker:

  1. Go to the Workers & Pages section in the Cloudflare dashboard.
  2. Click on "Create a Service" and choose the "HTTP Handler" template.
  3. This will provide you with a basic template to start with.

Step 2: Writing the Worker Script

Now, let's write a simple Worker script to generate an image based on a text prompt. Here's a basic example using the @cf/stabilityai/stable-diffusion-xl-base-1.0 model:

export default {
  async fetch(request, env) {
    const inputs = {
      prompt: 'cyberpunk cat',
    };

    const response = await env.AI.run(
      '@cf/stabilityai/stable-diffusion-xl-base-1.0',
      inputs,
    );

    return new Response(response, {
      headers: {
        'content-type': 'image/png',
      },
    });
  },
};
Enter fullscreen mode Exit fullscreen mode

Step 3: Getting the Prompt from the URL

To make your image generator dynamic, you can fetch the prompt from the URL query parameters. Here's how you can modify the above script:

export default {
  async fetch(request, env) {
    const url = new URL(request.url);
    const prompt = url.searchParams.get('prompt') || 'cyberpunk cat';

    const inputs = {
      prompt: prompt,
    };

    const response = await env.AI.run(
      '@cf/stabilityai/stable-diffusion-xl-base-1.0',
      inputs,
    );

    return new Response(response, {
      headers: {
        'content-type': 'image/png',
      },
    });
  },
};
Enter fullscreen mode Exit fullscreen mode

Now, users can generate images by visiting a URL like https://your-worker-url.workers.dev/?prompt=sunset beach.

Step 4: Customizing the Image Generation

Cloudflare's AI SDK allows you to customize the image generation process with various parameters. Some additional options you can use include:

  • Image Size: Specify the dimensions of the generated image.
  • Sampling Steps: Control the number of diffusion steps used, which can affect image quality and generation time.
  • Guidance Scale: Adjust how closely the generated image should follow the prompt.
  • Seed: Set a seed value for reproducibility.

Here’s how to integrate some of these options:

export default {
  async fetch(request, env) {
    const url = new URL(request.url);
    const prompt = url.searchParams.get('prompt') || 'cyberpunk cat';
    const width = parseInt(url.searchParams.get('width')) || 512;
    const height = parseInt(url.searchParams.get('height')) || 512;
    const steps = parseInt(url.searchParams.get('steps')) || 50;
    const guidanceScale = parseFloat(url.searchParams.get('guidance')) || 7.5;

    const inputs = {
      prompt: prompt,
      width: width,
      height: height,
      steps: steps,
      guidance_scale: guidanceScale,
    };

    const response = await env.AI.run(
      '@cf/stabilityai/stable-diffusion-xl-base-1.0',
      inputs,
    );

    return new Response(response, {
      headers: {
        'content-type': 'image/png',
      },
    });
  },
};
Enter fullscreen mode Exit fullscreen mode

Additional Features with Cloudflare's AI Gateway

Cloudflare's AI Gateway enhances the reliability and scalability of AI applications. It provides observability features, cost management tools like caching and rate limiting, and ensures that your application can handle high traffic efficiently. These features make it easier to manage and scale your AI-powered applications【20†source】【21†source】.

Conclusion

By leveraging Cloudflare Workers and its AI SDK, you can easily create a robust AI image generator. With the ability to customize image generation and the support of Cloudflare's scalable infrastructure, you can deploy a powerful AI application at the edge, close to your users.

Top comments (1)

Collapse
 
sh20raj profile image
Sh Raj