Skip to content

Commit fe8328f

Browse files
RobertCraigiestainless-app[bot]
authored andcommitted
docs(examples): add UI generation example script
1 parent 8b1b4b3 commit fe8328f

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

examples/ui-generation.ts

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
import OpenAI from 'openai';
2+
import { z } from 'zod';
3+
import { zodResponseFormat } from 'openai/helpers/zod';
4+
5+
const openai = new OpenAI();
6+
7+
// `z.lazy()` can't infer recursive types so we have to explicitly
8+
// define the type ourselves here
9+
interface UI {
10+
type: 'div' | 'button' | 'header' | 'section' | 'field' | 'form';
11+
label: string;
12+
children: Array<UI>;
13+
attributes: {
14+
value: string;
15+
name: string;
16+
}[];
17+
}
18+
19+
const UISchema: z.ZodType<UI> = z.lazy(() =>
20+
z.object({
21+
type: z.enum(['div', 'button', 'header', 'section', 'field', 'form']),
22+
label: z.string(),
23+
children: z.array(UISchema),
24+
attributes: z.array(
25+
z.object({
26+
name: z.string(),
27+
value: z.string(),
28+
}),
29+
),
30+
}),
31+
);
32+
33+
async function main() {
34+
const completion = await openai.beta.chat.completions.parse({
35+
model: 'gpt-4o-2024-08-06',
36+
messages: [
37+
{
38+
role: 'system',
39+
content: 'You are a UI generator AI. Convert the user input into a UI.',
40+
},
41+
{ role: 'user', content: 'Make a User Profile Form' },
42+
],
43+
response_format: zodResponseFormat(UISchema, 'ui'),
44+
});
45+
46+
const message = completion.choices[0]!.message;
47+
const ui = message.parsed;
48+
console.dir(ui, { depth: 10 });
49+
}
50+
51+
main();

0 commit comments

Comments
 (0)