Last active
July 26, 2024 09:27
-
-
Save GoodBoyDigital/0275a1a23b83065ff10cf4f0e2cc66cf to your computer and use it in GitHub Desktop.
An example of how to use zod (https://www.npmjs.com/package/zod) to get a structured result from OpenAI
This file contains hidden or 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
async function makeOpenAICall({ style, theme }: { style: string; theme: string }) { | |
/** | |
* set up a schema for the result using zod (https://www.npmjs.com/package/zod). we can then use this schema to tell open ai how to format the result | |
* it will use the descriptions to figure our what to but in each property.. | |
* | |
*/ | |
const resultSchema = z.object({ | |
name: z.string().describe('The name of the game'), | |
backgroundPrompt: z.string().describe('A midjourney prompt for the game background image '), | |
}); | |
const response = await openai.chat.completions.create({ | |
model: 'gpt-4o', | |
tools: [ | |
{ | |
type: 'function', | |
function: { | |
name: 'classify', | |
parameters: zodToJsonSchema(resultSchema), | |
}, | |
}, | |
], | |
tool_choice: { | |
type: 'function', | |
function: { | |
name: 'classify', | |
}, | |
}, | |
messages: [ | |
{ | |
role: 'system', | |
content: 'You are a creative director looking to create an amazing mobile game.', | |
}, | |
{ | |
role: 'user', | |
content: [ | |
{ | |
type: 'text', | |
text: `create me a theme and style for a match 3 game screen based in the following theme and style: | |
Style: ${style} | |
Theme: ${theme} | |
`, | |
}, | |
], | |
}, | |
], | |
}); | |
const choice = response.choices[0]!; | |
// parse the result using Zod schema. This will error out if the result does not fit the schema | |
// will return {name:'...', backgroundPrompt:'...'} | |
return resultSchema.parse(JSON.parse(choice.message.tool_calls![0]!.function.arguments)); | |
} | |
// const result = async function makeOpenAICall({ style:'cartoon', theme:'space' }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment