Poemly
Tags: cloudflarechallenge, devchallenge, ai
Published: 2024-04-15 07:06:21

*This is a submission for the [Cloudflare AI Challenge](https://dev.to/devteam/join-us-for-the-cloudflare-ai-challenge-3000-in-prizes-5f99).*

## What We Built

Welcome to Poemly! Our app harnesses the power of AI to craft beautiful poems tailored to your input. Whether you're seeking inspiration, exploring emotions, or simply curious about the art of poetry, Poemly is here to transform your words into heartfelt verses. With just a few prompts from you, our Cloudflare's Worker AI model delves into the depths of language and creativity to compose unique and evocative poems. 

Experience the magic of poetry like never before with Poemly – your personal muse in the digital age.

## Demo

{% embed https://poemly.pages.dev/ %}


![Poemly](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fxtj7nr9gpfhc8sc3boq.png)


## My Code

{% embed https://github.com/SanjayAlagappan/poemly %}

## Journey

My team and I embarked on the journey of creating a poem generator, and we began by brainstorming ideas to lay the foundation. After much discussion, we outlined the essential parameters required from the user to ensure the effective generation of poems. These parameters include the prompt or theme, the desired length of the poem, the tone of the poem, and the preferred style or form of poetry.

Then we transitioned to the design phase using Figma. Here, we crafted drafts to visualize the user interface and experience. These drafts serve as blueprints for our project.

![Poemly Generate Draft Design 1](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/esy08uk1kq16bb471ooh.png)

![Poemly Generate Draft Design 2](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3y5ccd4a1uzpxsxwd5bf.png)
 
After experimenting with various AI models available in [Cloudflare's AI model playground](https://playground.ai.cloudflare.com/), we settled on a specific prompt that effectively captures the essence of what we aim to achieve: generating personalized poems based on user input.

To achieve this, we've deployed two [worker AI](https://developers.cloudflare.com/workers-ai/) models on the backend. One is dedicated to generating text, crafting poetic verses tailored to the given prompt and user inputs. The other focuses on generating images, complementing the poetic experience with visual elements.

This is the code for the Text-Generation worker AI. We have used `@cf/meta/llama-2-7b-chat-fp16` model for it.


```typescript
// src/index.ts
var src_default = {
  async fetch(request, env) {
    const body = await request.text();
    const bodyObject = JSON.parse(body);
    const { prompt, length, tone, style } = bodyObject;
    console.log("Prompt:", prompt, length, tone, style);
    const messages = [
      { role: "system", content: "You are an assistant helps in generating poems based on the user input. Create a title for the same at the beginning and then the poem." },
      {
        role: "user",
        content: prompt,
        length,
        tone,
        style
      }
    ];
    const response = await env.AI.run("@cf/meta/llama-2-7b-chat-fp16", { messages });

    // Create a new Response object
    const corsHeaders = {
      "Access-Control-Allow-Origin": "*", // Allow requests from all origins
      "Access-Control-Allow-Methods": "GET, POST, OPTIONS", // Allow GET, POST, and OPTIONS requests
      "Access-Control-Allow-Headers": "Content-Type" // Allow the Content-Type header
    };
    
    return new Response(JSON.stringify({ response }), {
      headers: {
        ...corsHeaders,
        "Content-Type": "application/json"
      }
    });
  }
};

export {
  src_default as default
};
//# sourceMappingURL=index.js.map

```

**Multiple Models**

As mentioned, We have used another model: `@cf/stabilityai/stable-diffusion-xl-base-1.0` for the image generation. Here is the code for the same.

```typescript
// src/index.ts
var src_default = {
  async fetch(request, env) {
    // Parse the request body
    const body = await request.text();
    const bodyObject = JSON.parse(body);
    const prompt = bodyObject.prompt;

    // Define the inputs for the AI model
    const inputs = {
      prompt: prompt
    };

    // Run the AI model to generate the image
    const response = await env.AI.run(
      "@cf/stabilityai/stable-diffusion-xl-base-1.0",
      inputs
    );

    // Create a new Response object
    const corsHeaders = {
      "Access-Control-Allow-Origin": "*", // Allow requests from all origins
      "Access-Control-Allow-Methods": "GET, POST, OPTIONS", // Allow GET, POST, and OPTIONS requests
      "Access-Control-Allow-Headers": "Content-Type" // Allow the Content-Type header
    };

    // Return the response with CORS headers
    return new Response(response, {
      headers: {
        ...corsHeaders,
        "Content-Type": "image/png"
      }
    });
  }
};
export {
  src_default as default
};

```

We encountered various issues during the development process, particularly with CORS (Cross-Origin Resource Sharing) errors. To address this, we experimented with different methods and configurations. To troubleshoot and test our solutions, we utilized Postman. We got the solution from the Cloudflare Discord Community. 

![Worker AI Metrics](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m7gkymxxcf3o7ra0d7qm.png)

![Cloudflare Discord Community](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uxiuezgx8kx8vvrrpbnc.png)


Cloudflare has been a fascinating new territory for all of us, and this challenge provided a fantastic opportunity to dive into its services and learn extensively. Exploring the Cloudflare ecosystem has been both educational and enjoyable.

As for Poemly, our journey doesn't end here. There's still more to come. We have planned to create an explore page, where users can see all the generated poems. Unfortunately, due to time constraints, we haven't been able to implement it yet. It's an essential feature that we believe will enrich the Poemly experience and foster a vibrant community of poetry enthusiasts. So, stay tuned!

Thanks for the read!

Team members - @sanjayalagappan @sibims @mohandotdev @santoholic