DEV Community

Enrique Aguilar Martinez
Enrique Aguilar Martinez

Posted on • Edited on

Steps to build a text generator application in workers ai by cloudflare

The Cloudflare AI Challenge
By Enrique Aguilar Martinez Cloud Engineer.
Cloudflare is one of the largest networks on the Internet, Cloudflare 's interest in AI arises from its mission to "make the Internet faster, more secure and more reliable." The company sees AI as a powerful tool for every user.
On this occasion I bring you a tutorial to implement a text generating application ( javascrip code) with Watson (IBM) models.
First go to the Cloudflare page

Image description
In this page
Sign in to your Cloudflare account at https://dash.cloudflare.com/.
Click Workers in the left sidebar.
Click on works and pages .

Image description
In name put the name of the project

Image description
In this part, your project is now online in Cloudflare and can be deployed.

Image description
Here you can edit your code with which you are going to deploy the project.

Image description
You delete it and apply the code that may be in javascrip .

Image description
In this case the text generator.
You give it deploy, you save the changes and it generates 200

Image description
Remember that Cloudflare Workers supports two main syntaxes for writing worker scripts:
• Service Worker Syntax: This is the older syntax and addEventListener is used to register event handlers.
• Module Syntax: This is the newer syntax and export default is used to define the function of the controller.
If you are using module syntax, you must configure Cloudflare Wrangler (the deployment tool) to recognize it.

Image description
This on the Cloudflare console side , to upload it remotely just open cmd on your local machine and first of all see what you want to implement.

Define the use case:
What type of text do you want to generate? (e.g. product descriptions, blog articles, scripts) How long should the text be? What writing style do you want to use? (e.g. formal, informal, creative)

Image description
Install in cmd : npm install -g npm
npm command install -g npm , is used to install NPM globally on the system. NPM ( Node Package Manager) is an essential tool for developing JavaScript applications, as it allows us to easily install, manage and update libraries and code modules.
Remember that:
• npm : It is the command to run the NPM tool.
• install : Indicates that you want to install something.
• -g: Means "global". This flag tells NPM to install the specified package globally, making it accessible from anywhere on the system.
• npm : It is the name of the package you want to install, in this case, NPM itself.

Image description
This is installed globally
Installing NPM globally means that you will have it available in any directory on your computer, no matter what project you are working on. This allows you to run NPM commands from anywhere, without having to navigate to a specific directory.
Install -Module -Name cloudflare
Install -Module - Name command Cloudflare is used to install the Cloudflare Module for PowerShell on the system. This module allows us to manage your Cloudflare DNS zones directly from the PowerShell command line (CMD)
Command explanation:
• Install -Module: It is the PowerShell command to install modules.
• - Name : Indicates the name of the module that you want to install.
• Cloudflare : This is the name of the module you want to install, in this case, the Cloudflare module for PowerShell.
What does the Cloudflare module for PowerShell do?
Cloudflare Module for PowerShell allows you to perform a variety of tasks related to your Cloudflare DNS zones , such as:
• Create, update and delete DNS records
• Configure advanced DNS records, such as CNAME records and MX records
• Set firewall rules for your DNS zone
• View the change history of your DNS zone
• Manage your DNS zones automatically using PowerShell scripts

Image description
Install -Module -Name cloudflare
Install -Module - Name command Cloudflare is used to install the Cloudflare Module for PowerShell on the system. This module allows us to manage Cloudflare DNS zones directly from the PowerShell command line.
Command explanation:
• Install -Module: It is the PowerShell command to install modules.
• - Name : Indicates the name of the module that you want to install.
• Cloudflare : This is the name of the module you want to install, in this case, the Cloudflare module for PowerShell.
In the wishes part you enter enter until you reach the display part.

Image description
npx wrangler dev –remote
Here you are asked to log in to bypass the Shell.
npx command wrangler dev --remote is used to start a local development environment for a Wrangler application on the system.
Command explanation:
• npx : It is a Node.js package that allows us to execute JavaScript commands without having to install them globally.
• wrangler : It is the command line (CLI) tool for Wrangler, a platform for developing and deploying serverless web applications.
• dev : Indicates that you want to start a local development environment.
• --remote: This flag tells Wrangler to use a remote server to run the application. This means the app will run on a Wrangler server in the cloud, rather than on the local computer.
What do you do when starting a remote local development environment?
When starting a remote local development environment with npx wrangler dev --remote, Wrangler creates a remote server in the cloud and runs the application on that server. This allows us:
• Develop the application in the local environment , using the code editor in this case Visual Studio and the development tools that are required.
• See changes to your application in real time , without having to deploy your application to a production environment.
• Test the application on different browsers and devices , using the browser's debugging tools.

Image description
Within Visual Studio you can see all the packages that it installs in the module command, you can see that there is already a js template and a tombl with which it is for the configuration and the creation of environment variables.
In this part you can select option b, which is where the js script is already linked , to view the application within the clouflare console no longer as localhost.

Image description

Image description
npx wrangler deploy
npx command wrangler deploy is used to publish the Cloudflare application Worker on the Cloudflare global network . In other words, this command allows us to make the application available on the internet.
Command explanation:
• npx : It is a Node.js package that allows you to execute JavaScript commands without having to install them globally.
• wrangler : It is the command line (CLI) tool for Wrangler, a platform for developing and deploying serverless web applications.
• deploy : Indicates that you want to deploy your application to the Cloudflare network .
What happens when you run npx wrangler deploy ?
When you run this command, Wrangler does the following:

  1. Worker code : Wrangler looks for your Worker 's main file , which by convention is usually called wrangler.js or index.js.
  2. Package your code: Wrangler packages Worker code along with any necessary dependencies.
  3. Upload your code to Cloudflare : Wrangler uploads packaged code to the Cloudflare global network .
  4. Configure your Worker : Wrangler configures the Worker on the Cloudflare network , assigning it a unique URL.
  5. Provides you with the URL of your Worker : Once the deployment has completed successfully, Wrangler will show you the URL of your deployed Worker .

Here you implement the code:
`

`//Import libraries
const { TextToSpeech } = require(' watson -developer-cloud');
const { CloudFunctions } = require(' cloudflare -workers');

// Access credentials from environment variables
const username = process.env.WATSON _USERNAME ;
const password = process.env.WATSON _PASSWORD ;
const url = 'https://stream.watsonplatform.net/text-to-speech/api ' ;

// Initialize Watson TextToSpeech client
const tts = new TextToSpeech ( {
username,
password,
url ,
});

// CloudFunctions instance
const cf = new CloudFunctions ( );

// Function to generate audio from text
async function generateText ( prompt, model, temperature, maxTokens ) {
try {
const response = await tts.synthesize ({
text:prompt,
voice: model,
temperature,
max_tokens ,
});
return response.audio ;
} catch (error) {
console.error ('Error generating text :', error);
// Handle the error appropriately (eg, return an error response)
return new Response( 'Error generating text', { status: 500 });
}
}

// Function to handle HTTP requests
async function handleRequest (request) {
const { prompt , model, temperature, maxTokens } = await request.json ();

const audio = await generateText ( prompt, model, temperature, maxTokens );

return new Response( audio, {
headers: {
'Content-Type': 'audio/wav',
},
});
}

// Register the HTTP request handler
cf.registerRoute ('POST', '/', handleRequest );

// Export the CloudFunctions instance
module.exports = cf ;
`
**_
Image description

Thank you very much for viewing this article, at other times share more about CLOUDFLARE._**

Link GitHub repo:
https://github.com/EnriqueAguila/CloudflareAI.git

Top comments (1)

Collapse
 
felino33 profile image
felino33

Extraordinary journey through #Cloudflare workers AI, and the ease of implementing a Generative AI model in javascript