strapi-open-ai-text-generation
strapi-plugin-field-formula
Our great sponsors
strapi-open-ai-text-generation | strapi-plugin-field-formula | |
---|---|---|
1 | 1 | |
10 | 6 | |
- | - | |
10.0 | 8.2 | |
about 1 year ago | 2 months 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-field-formula
-
Open Source: Strapi v4 - Formula field
I'm glad to introduce you to the powerful math operations just inside your Headless CMS and to invite you for contributing!
What are some alternatives?
strapi-tiptap-editor - A drop-in replacement for the strapi editor
strapi-plugin-transformer - A plugin for Strapi Headless CMS that provides the ability to transform the API request or response.
strapi-plugin-config-sync - :recycle: CLI & GUI for continuous migration of config data across environments
Engineering-Solver - Engineering Solver helps to do calculations with units and thermodynamic properties in a very fast way.
strapi-plugin-sitemap - 🔌 Generate a highly customizable sitemap XML in Strapi CMS
Strapi - 🚀 Strapi is the leading open-source headless CMS. It’s 100% JavaScript/TypeScript, fully customizable and developer-first.
mathjs - An extensive math library for JavaScript and Node.js