-
Notifications
You must be signed in to change notification settings - Fork 1k
/
Copy pathui-generation.ts
51 lines (45 loc) · 1.22 KB
/
ui-generation.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
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();