-
Notifications
You must be signed in to change notification settings - Fork 876
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
docs(examples): add UI generation example script
- Loading branch information
1 parent
cb54d93
commit c75c017
Showing
1 changed file
with
51 additions
and
0 deletions.
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,51 @@ | ||
import OpenAI from 'openai'; | ||
import { z } from 'zod'; | ||
import { zodResponseFormat } from 'openai/helpers/zod'; | ||
|
||
const openai = new OpenAI(); | ||
|
||
// `z.lazy()` can't infer recursive types so we have to explicitly | ||
// define the type ourselves here | ||
interface UI { | ||
type: 'div' | 'button' | 'header' | 'section' | 'field' | 'form'; | ||
label: string; | ||
children: Array<UI>; | ||
attributes: { | ||
value: string; | ||
name: string; | ||
}[]; | ||
} | ||
|
||
const UISchema: z.ZodType<UI> = z.lazy(() => | ||
z.object({ | ||
type: z.enum(['div', 'button', 'header', 'section', 'field', 'form']), | ||
label: z.string(), | ||
children: z.array(UISchema), | ||
attributes: z.array( | ||
z.object({ | ||
name: z.string(), | ||
value: z.string(), | ||
}), | ||
), | ||
}), | ||
); | ||
|
||
async function main() { | ||
const completion = await openai.beta.chat.completions.parse({ | ||
model: 'gpt-4o-2024-08-06', | ||
messages: [ | ||
{ | ||
role: 'system', | ||
content: 'You are a UI generator AI. Convert the user input into a UI.', | ||
}, | ||
{ role: 'user', content: 'Make a User Profile Form' }, | ||
], | ||
response_format: zodResponseFormat(UISchema, 'ui'), | ||
}); | ||
|
||
const message = completion.choices[0]!.message; | ||
const ui = message.parsed; | ||
console.dir(ui, { depth: 10 }); | ||
} | ||
|
||
main(); |