[Video] Let's Build a DALLE-3 UI Using Elixir & Livebook

Video

Code

openai_api_key = System.fetch_env!("LB_OPENAI_API_KEY")

form =
  Kino.Control.form(
    [
      prompt: Kino.Input.textarea("Prompt"),
      size:
        Kino.Input.select(
          "Image size",
          ["1024x1024", "1792x1024", "1024x1792"] |> Enum.map(&{&1, &1})
        )
    ],
    submit: "Generate"
  )

frame = Kino.Frame.new()

Kino.listen(form, fn %{data: %{prompt: prompt, size: size}} ->
  IO.inspect("Generating...")

  case Req.post("https://api.openai.com/v1/images/generations",
         json: %{model: "dall-e-3", prompt: prompt, n: 1, size: size},
         auth: {:bearer, openai_api_key}
       ) do
    {:ok, response} ->
      IO.inspect("Got url")
      [image | _] = response.body["data"]
      image_url = image["url"]

      image_contents = Req.get!(image_url).body

      Kino.Frame.append(frame, Kino.Image.new(image_contents, :png))

    _ ->
      nil
  end
end)

Kino.Layout.grid([form, frame])