Learn how to build a full-stack Next.js app that can generate React apps with a single prompt.
createApp
, since it’s going to take the user’s prompt and generate the corresponding app code:
/api/generateCode
, and we’ll make it a POST endpoint so we can send along the prompt
in the request body:
route.js
file:
together.chat.completions.create
to get a new response from the LLM. We’ve supplied it with a “system” message telling the LLM that it should behave as if it’s an expert React engineer. Finally, we provide it with the user’s prompt as the second message.
Since we return a JSON object, let’s update our React code to read the JSON from the response:
<Sandpack>
component to render and execute any code we want!
Let’s give it a shot with some hard-coded sample code:
generatedCode
:
generatedCode
is not empty, we can render <Sandpack>
and pass it in:
<Sandpack>
renders our generated app!
stream: true
option into together.chat.completions.create()
. We also need to update our response to call res.toReadableStream()
, which turns the raw Together stream into a newline-separated ReadableStream of JSON stringified values.
Here’s what that looks like:
res.json()
it. We need a small helper function to read the text from the actual bytes that are being streamed over from our API route.
Here’s the helper function. It uses an AsyncGenerator to yield out each chunk of the stream as it comes over the network. It also uses a TextDecoder to turn the stream’s data from the type Uint8Array (which is the default type used by streams for their chunks, since it’s more efficient and streams have broad applications) into text, which we then parse into a JSON object.
So let’s copy this function to the bottom of our page:
createApp
function to iterate over readStream(res.body)
:
for...of
to iterate over each chunk right in our submit handler!
By setting generatedCode
to the current text concatenated with the new chunk’s text, React automatically re-renders our app as the LLM’s response streams in, and we see <Sandpack>
updating its UI as the generated app takes shape.