strapi-open-ai-text-generation
strapi-plugin-config-sync
Our great sponsors
strapi-open-ai-text-generation | strapi-plugin-config-sync | |
---|---|---|
1 | 3 | |
10 | 235 | |
- | 0.4% | |
10.0 | 8.1 | |
about 1 year ago | 9 days ago | |
JavaScript | JavaScript | |
- | MIT License |
Stars - the number of stars that a project has on GitHub. Growth - month over month growth in stars.
Activity is a relative number indicating how actively a project is being developed. Recent commits have higher weight than older ones.
For example, an activity of 9.0 indicates that a project is amongst the top 10% of the most actively developed projects that we are tracking.
strapi-open-ai-text-generation
-
Building a Strapi Custom Field for Text Generation with Open AI
: acts as our input for prompts; we use onChange() ‘watcher’ to update the value of our prompt state as we type data. We then store the prompt in a variable called prompt. TextArea />: is what we use to store the value of our generated text. We use a to edit the generated text. We use a special implementation of our
onChange()
watcher, which allows us to pass an object of multiple values to update when a change occurs in that component.We also have two buttons where all the magic happens. One button calls
generateText()
- this function usesfetch
to call our backend service,/ai-text-generation/generate-text
that makes authenticated calls to the Open AI API (we’ll create this next). To authenticate this, we useauth
from@strapi/helper-plugin
which helps us make a secure request to the Strapi service we’ll create using the Admins token.We then parse our result and use the special implementation of
onChange()
to pass the parsed response as the content that will get added to our database withonChange({ target: { name, value: parsedResult, type: attribute.type } })
.The other button calls
clearGeneratedText()
- this function clears all the text the AI generated in case we want to start over. At this point, our application should look something like this.Building a Custom Open AI Route in Strapi
To access Open AI, we need to provide an API KEY; having this key in the admin poses a security risk, and to combat that, we’ll create a custom route that, when called, makes an API call to Open AIs API and returns the generated text that we can then send to the admin.
So start, in our
./config/plugins.js
file add a config object belowenabled: true
, your config file after should look like this:
// … 'ai-text-generation': { enabled: true, config: { apiToken: process.env.OPEN_AI_API_TOKEN, }, resolve: './src/plugins/ai-text-generation' },
Enter fullscreen mode Exit fullscreen modeNow, create a file called
open-ai.js
in./src/plugins/ai-text-generation/server/services
and paste the following code in it.For the code to work, you will also have to install axios, for that navigate to your plugin root and type
yarn add axios
'use strict'; const axios = require('axios'); module.exports = ({ strapi }) => ({ async generateText(prompt) { try { const response = await axios( { url: 'https://api.openai.com/v1/completions', method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${strapi.plugin('ai-text-generation').config('apiToken')}` }, data: JSON.stringify({ 'model': 'text-davinci-001', 'prompt': `${prompt}`, 'temperature': 0.4, 'max_tokens': 64, 'top_p': 1, 'frequency_penalty': 0, 'presence_penalty': 0 }) }) return response.data; } catch (err) { console.log(err.response) } } });
Enter fullscreen mode Exit fullscreen modeHere we define a function
generateText()
that takes a prompt as an argument. We then use prompt as a parameter in our request to Open AI.Next up, in the same services folder, paste the following code in your
index.js
file.
'use strict'; const openAi = require('./open-ai'); module.exports = { openAi, };
Enter fullscreen mode Exit fullscreen modeThis code registers a service in Strapi that we call from a controller, before we do that. We need to create a controller. In
./src/plugins/ai-text-generation/server/controllers
, create a file calledai-controller.js
and paste the following code in it:
'use strict'; module.exports = ({ strapi }) => ({ async generate(ctx) { ctx.body = await strapi .plugin('ai-text-generation') .service('openAi') .generateText(ctx.request.body.prompt); }, });
Enter fullscreen mode Exit fullscreen modeIn this file, we call the
generateText()
function that we defined in the service we just made and passctx.request.body.prompt
(from our POST request).In the same folder, we need to paste the following code in our
index.js
file:
'use strict'; const aiController = require('./ai-controller'); module.exports = { aiController, };
Enter fullscreen mode Exit fullscreen modeLastly, we must create a route to access the controller we just created. In
./src/plugins/ai-text-generation/server/routes
we need to paste the following code:
module.exports = [ { method: 'POST', path: '/generate-text', handler: 'aiController.generate', config: { policies: [], }, }, ];
Enter fullscreen mode Exit fullscreen modeIn this file, we define how our endpoint should behave. With this code, we create a
POST
method on the/generate-text
URI and pass theaiController
controller we created to define its behavior.In your preferred API client, you can now make a request to
localhost:1337/ai-text-generation/generate-text
and you should get AI-generated text as a response. Be sure to add your prompt as a parameter and pass your admin JWT for authentication.We should also get a response when we enter a prompt and click “generate” in our Custom Field.
Publishing to npm
Maxime from the Strapi team wrote an amazing article on how to publish your plugin to npm, and if you have any trouble you can refer to my package.json file for how to structure yours.
You can also take your Custom field to the next level and submit it to the official Strapi marketplace.
Hopefully, you have a better idea of how to build Custom fields now, and even better, you have a custom field that generates content for you with Open AI.
Let us know if you build something, the Strapi community will be excited to try it out. Take care.
strapi-plugin-config-sync
-
Goodbye 2022, Hello 2023! Strapi Wrapped in One Year
Strapi wouldn’t be anything without its community, which is very much represented by its Community Stars. The Write for the Community program resulted in 148 new articles being published, for a total of 1.3M views. 2022 was also the year of the launch of the Strapi Community Organization, a group of community members dedicated to empowering initiatives and highlighting them. Boaz, Mattie, Sacha, and Simen have been invaluable contributors to the Strapi Community, going above and beyond by developing open-source plugins and tools. Strapi config-sync plugin, mattie-strapi-bundle (for search), Strapi REST cache plugin, Dockerize tool, and more!
-
Re-Introducing the Strapi Community Organization
Boaz, Developer and creator of the Strapi config-sync plugin.
-
The Strapi Config Sync Plugin
For the config-sync plugin specifically, I would love to have environment specific configs, allowing you to have different configs for staging/acceptance/production. This is not really a big issue yet, but as soon as we start getting more complex plugins that store their config in the database this can become very crucial. There is an issue for that on the GitHub repo.
What are some alternatives?
strapi-tiptap-editor - A drop-in replacement for the strapi editor
strapi-tool-deployify - Easy deploy strapi to cloud platforms
strapi-plugin-transformer - A plugin for Strapi Headless CMS that provides the ability to transform the API request or response.
strapi-tool-dockerize - Easy add support for docker to your strapi project
strapi-plugin-field-formula - A plugin for Strapi Headless CMS that provides an integration with powerful mathjs library.
strapi-webtools - 🔗 Unique, flexible and autogenerated URLs for your Strapi managed web content.
strapi-plugin-sitemap - 🔌 Generate a highly customizable sitemap XML in Strapi CMS
website - The repo for the website development competition of the @strapi-community.
community-content - Contribute and collaborate on educational content for the Strapi Community
strapi-plugin-rest-cache - Speed-up HTTP requests with LRU cache.
awesome-strapi - A curated list of awesome things related to Strapi
mattie-strapi-bundle - Mattie plugin bundle for Strapi