From c75c017c16cbfe3fc60ea4ee5779782005e64463 Mon Sep 17 00:00:00 2001 From: Robert Craigie Date: Wed, 7 Aug 2024 14:20:59 +0100 Subject: [PATCH] docs(examples): add UI generation example script --- examples/ui-generation.ts | 51 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 examples/ui-generation.ts diff --git a/examples/ui-generation.ts b/examples/ui-generation.ts new file mode 100644 index 000000000..84636b1f0 --- /dev/null +++ b/examples/ui-generation.ts @@ -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; + attributes: { + value: string; + name: string; + }[]; +} + +const UISchema: z.ZodType = 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();