Last active
January 12, 2023 19:41
-
-
Save rdraward/3dc5e6789993dd7c2084f8c653f75e1d to your computer and use it in GitHub Desktop.
Sample code file for Gadget + ChatGPT copywriter that updates Shopify product descriptions based on tag input
This file contains 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
const { Configuration, OpenAIApi } = require("openai"); | |
/** | |
* Effect code for update on Shopify Product | |
* @param { import("gadget-server").UpdateShopifyProductActionContext } 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, connections }) => { | |
const configuration = new Configuration({ | |
apiKey: process.env.OPENAI_API_KEY, | |
}); | |
const openai = new OpenAIApi(configuration); | |
// get tags for changed shopifyProduct | |
const productTags = record.tags; | |
// find first applicable prompt, if it matches a passed-in tag | |
let gptPrompt; | |
try { | |
gptPrompt = await api.descriptionPrompt.findFirst({ | |
filter: { | |
tag: { | |
in: productTags | |
} | |
}, | |
select: { | |
tag: true, | |
prompt: true | |
} | |
}); | |
} catch { | |
logger.info({ productTags }, "Error fetching GPT prompts - maybe there is no matching tag?") | |
} | |
if (gptPrompt) { | |
let newProductDescription; | |
try { | |
const completion = await openai.createCompletion({ | |
model: "text-davinci-002", | |
prompt: `This is a Shopify product titled '${record.title}' with description: ${record.body}. ${gptPrompt.prompt} Use text speaking to the buyer. Return the new description with HTML markup <p> for paragraphs and <br> for line breaks. Use at most 200 words.`, | |
temperature: 0, | |
max_tokens: 250, | |
top_p: 1, | |
frequency_penalty: 0.0, | |
presence_penalty: 0.0, | |
}); | |
newProductDescription = completion.data.choices[0].text; | |
} catch (error) { | |
logger.error({ error }, "Error sending request to OpenAI client"); | |
} | |
// remove tag from array of product tags | |
productTags.splice(productTags.indexOf(gptPrompt.tag), 1); | |
const shopify = await connections.shopify.current; | |
if (shopify && newProductDescription) { | |
await shopify.product.update(parseInt(record.id), { | |
tags: productTags, | |
body_html: newProductDescription, | |
}); | |
logger.info({ newProductDescription }, `Updating product id ${record.id} with new description`); | |
} | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment