-
-
Save suhanlee/4c38bcd9f625774b58ef779d68b04ff8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Mix.install( | |
[ | |
{:phoenix_playground, "~> 0.1.0"}, | |
{:openai, "~> 0.6.1"} | |
], | |
config: [ | |
openai: [ | |
api_key: System.get_env("OPENAI_API_KEY"), | |
organization_key: System.get_env("OPENAI_ORGANIZATION_KEY") | |
] | |
] | |
) | |
defmodule ContainerLive do | |
use Phoenix.LiveView | |
def mount(_params, _session, socket) do | |
{:ok, assign(socket, view: nil)} | |
end | |
def render(assigns) do | |
assigns = assign(assigns, changeset: %{}) | |
~H""" | |
<div :if={not is_nil(@view)}> | |
<%= live_render(@socket, @view, id: "#{@view}-view") %> | |
</div> | |
<.form for={@changeset} phx-submit="generate_view"> | |
<h1>Generate a view</h1> | |
<p>Enter a prompt to generate a view.</p> | |
<p>Write a simple Elixir Phoenix LiveView module that...</p> | |
<textarea rows={4} columns={50} name="prompt" /> | |
<button type="submit">Generate view</button> | |
</.form> | |
""" | |
end | |
def handle_event("generate_view", %{"prompt" => prompt}, socket) do | |
{:ok, %{choices: [%{"message" => %{"content" => view}}]}} = | |
OpenAI.chat_completion( | |
model: "gpt-4o", | |
messages: [ | |
%{role: "system", content: "You are a helpful assistant."}, | |
%{ | |
role: "user", | |
content: | |
"Write a simple Elixir Phoenix LiveView module that #{prompt}. Respond with nothing but the code for the module. Make sure the module is named simply 'NewView' (and nothing else, not 'MyAppWeb.NewView', for example)." | |
} | |
] | |
) | |
view |> String.trim("```") |> String.trim("elixir") |> Code.eval_string() | |
{:noreply, assign(socket, view: NewView)} | |
end | |
end | |
PhoenixPlayground.start(live: ContainerLive) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment