Last active
June 28, 2023 16:24
-
-
Save rdraward/32c7dd8aaba55a458e68770a9e325b2d to your computer and use it in GitHub Desktop.
Code snippet that calls OpenAI directly from the Gadgemon create action
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
| /** | |
| INSTRUCTIONS | |
| This gist relates to the Gadget quickstart, available here - https://docs.gadget.dev/guides/getting-started/quickstart | |
| - get an OpenAI API key (https://openai.com/) | |
| - add the key as an OPENAI_API_KEY Environment Variable in your Gadget app (Settings -> Environment Variables) | |
| - install the 'openai' npm package (open Gadget command palette, type '>' to enter command mode, enter 'yarn add openai') | |
| - paste the following snippet into the code file that runs on the Gadgemon's create action (gadgemon/create/onCreateSuccess.js) | |
| */ | |
| // in gadgemon/create/onCreateSuccess.js | |
| import { Configuration, OpenAIApi } from "openai"; | |
| // set up OpenAI client config | |
| const configuration = new Configuration({ | |
| apiKey: process.env.OPENAI_API_KEY, | |
| }); | |
| // init the OpenAI client | |
| const openai = new OpenAIApi(configuration); | |
| /** | |
| * Effect code for create on Pokemon | |
| * @param { import("gadget-server").CreateGadgemonActionContext } context - Everything for running this effect, like the api client, current record, params, etc. More on effect context: https://docs.gadget.dev/guides/extending-with-code#effect-context | |
| */ | |
| module.exports = async ({ api, record, params, logger }) => { | |
| // "record" is the newly created Gadgemon, with name, similar and type fields that will be added by the user | |
| const { id, name, similar, type } = record; | |
| const prompt = `A pixel art style pokemon sprite named ${name} that looks similar to a ${similar} that is a ${type} type. Do not include any text, including the name, in the image`; | |
| // make a request to OpenAI's DALL-E API | |
| const response = await openai.createImage({ | |
| prompt, | |
| n: 1, | |
| size: "256x256", | |
| }); | |
| const imageUrl = response.data.data[0].url; | |
| // write to the Gadget Logs | |
| logger.info({ imageUrl }, `Generated image URL for Gadgemon id ${id}`); | |
| // save the image file to the newly created Gadgémon record | |
| await api.gadgemon.update(id, { | |
| sprite: { | |
| copyURL: imageUrl | |
| } | |
| }); | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment