Intro to AI in Web Development

by: Kira Corbett

We are living in a time where things are buzzing – buzzing with words like AI (artificial intelligence) or ML (machine learning). Many think “AI is taking over the world!” No…AI is not taking over but it is certainly changing the way we are doing things. In this article, we’ll give a bird’s eye overview to this “buzz buzz” about AI, different applications for AI, and how you can get started.

Understanding AI: AI Under the Hood

When it comes to AI, many terms are often thrown around. However, they all work together much like a chef in a restaurant. A chef needs a variety of ingredients, recipes, and time to cook to perfect a recipe with the best combination of ingredients and methods. AI is similar. Just like a chef in a kitchen, AI needs ingredients (data), recipes (algorithms), and time to cook (trial and error to learn the best combinations of data and algorithms).

In this respect, artificial intelligence is the overarching system (the chef in our kitchen). AI mimics human intelligence by taking on complex tasks of computer systems that typically require human intelligence. Some of these tasks include learning - machine learning - which relies on lots of data to train it (the ingredients for our chef).

Other forms of tasks AI take on are often defined as neural networks which are computational models inspired by the human brain. Neural networks work to learn and understand patterns to make predictions, identify the best combinations, adapt, improve, and perform (this would be like our chef cooking many recipes with many ingredients and methodologies.) When multiple layers of neural networks are executed, this is referred to as deep learning.

So, now you can see why this word is buzzing around! There are so many topics and subfields to understand and learn how to work with AI.

AI in Web Development

AI has an abundance of applications in our experiences with technology. As a web developer, we can leverage some of these advantages such as automation, optimization, and even enhancements to our user facing pieces. Think about software you use on a daily basis. Chat systems on help pages, translation tools like text to image, object detection, or generative AI.

If you are interested in seeing how some current companies work with AI, here are a few use cases of AI on the web in various industries including content creation, web development, productivity, etc. In content creation, Swell AI is a great example of a SaaS that uses AI to write a brand in your voice by transcribing podcasts or videos into clips, notes, posts, and more. Brainstory AI also uses AI for content creation within the app to help evaluate, think through, and share ideas.

As a web developer and software engineer, Cursor is built on top of Visual Studio Code and offers developers their own personal “rubber duck” or AI to prompt directly about their current code.

Even apps like Monday are offering different ways to utilize AI to optimize productivity and organization to plan and manage products.

Essential Tools and Frameworks

A lot of tools and frameworks for utilizing AI and machine learning have become predominantly popular in Python. This is primarily due to the rich ecosystems of tools and libraries within Python but also ease of use as it is widely adopted and versatile. Python also has many tools for data sciences and open source adoption which plays largely into training computational models.

Major Frameworks for AI

  • TensorFlow - Considered an "end-to-end" machine learning platform primarily large-scale projects or production.
  • PyTorch - Another "end to end" machine learning framework primarily for research and experimentation.
  • Keras - An API for deep learning.

Major Frameworks for AI in Web Development

  • OpenAI - The official Node.js / TypeScript library for the OpenAI API (ChatGPT.)
  • The Vercel AI SDK - Open-source library for frontends based in JavaScript and TypeScript.

How to Get Started with AI in Your Web Development Project

We are going to create a little experiment utilizing the OpenAI API for Node.js. For this project, we will create an Ad Generator for our chef's restaurant.

We will:

  • Set up a simple React app for the frontend / user interactions
  • Configure OpenAI and integrate the API
  • Create a text prompt based model to generate requested content

1. Create a React app

npx create-react-app intro-to-ai

2. Install Node.js

To use the OpenAI library, you will need to have Node.js installed. You can download a package directly from the official website or via the terminal

MacOS

brew install node
node -v
npm -v

Windows

// Installation using cURL
curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.0/install.sh | bash
nvm –version

3. Install required libraries for OpenAI and axios

npm install --save openai

OR

yarn add openai

We will also need axios.

npm install axios

OR

yarn install axios

4. Get API keys

You will want to sign up for OpenAI to get an API key to use in your program.

You can either set up your API key for all your projects or specifically for this project. It is recommended that you set up your API key for all projects if you have multiple projects as it makes it accessible for all projects that use the SDK. However, for the sake of this project I am going to store mine in an .env file so that this API key is specific for this demo project. If you want more information to set up your API across all projects, you can look through Step 2 on OpenAI's documentation.

Once you sign-up, you can access the API Keys menu on the left hand side of the menu. Generate a new API key and store it safely for your personal use. Remember! Never commit your API keys.

5. Create our Ad Component

Create a new file called AdComponent.js and paste the following skeleton elements in for a simple user input form and button.

import React, { useState } from "react";
import axios from "axios";
import OpenAI from "openai";
import "./AdComponent.css";

const AdComponent = () => {
const [userInput, setUserInput] = useState("");
const [response, setResponse] = useState("");
const [typing, setTyping] = useState(false);

const handleUserInput = (e) => {
setUserInput(e.target.value);
};

return (
<div className="ad-container">
<h1 className="ad-title">Moon Highway Ad Generator</h1>
<textarea
className="ad-textarea"
value={userInput}
onChange={handleUserInput}
placeholder="Enter your prompt here"
/>
<button className="ad-button">Generate Response</button>
{typing && <p>Typing...</p>}
{response && (
<div>
<h3>Generated Ad:</h3>
<p>{response}</p>
</div>
)}
</div>
);
};

export default AdComponent;

Create a new file called AdComponent.css for some basic styling.

.container {
max-width: 800px;
margin: 0 auto;
padding: 20px;
border: 1px solid #ccc;
border-radius: 5px;
}

.ad-title {
font-size: 24px;
color: #007bff;
margin-bottom: 15px;
}

.ad-textarea {
width: 90%;
height: 100px;
padding: 10px;
margin-right: 50px;
margin-bottom: 15px;
border: 1px solid #ccc;
border-radius: 5px;
}

.ad-button {
background-color: #007bff;
color: #fff;
padding: 10px 20px;
border: none;
border-radius: 5px;
cursor: pointer;
}

.ad-button:hover {
background-color: #0056b3;
}

.ad-response {
margin-top: 20px;
}

.ad-response h3 {
font-size: 18px;
color: #333;
margin-bottom: 10px;
}

.ad-response p {
font-size: 16px;
color: #666;
}

Now let’s update our App.js file to reflect our new component.

import "./App.css";
import AdComponent from "./AdComponent";

function App() {
return (
<div className="App">
<AdComponent />
</div>
);
}

export default App;

You can now run npm start to view the skeleton site on localhost:3000.

6. Incorporate OpenAI

We will need to update AdComponent.js to incorporate the OpenAI library. This is where you will add your API key as well as create a generateResponse function which will send a POST request to the API to get a text-prompt response in return.

import React, { useState } from "react";
import axios from "axios";
import OpenAI from "openai";
import "./AdComponent.css";

const AdComponent = () => {
const [userInput, setUserInput] = useState("");
const [response, setResponse] = useState("");
const [typing, setTyping] = useState(false);

const apiKey = ""; // Your API key here
const apiUrl = "https://api.openai.com/v1/chat/completions";

const handleUserInput = (e) => {
setUserInput(e.target.value);
};

const openai = new OpenAI({
apiKey: "", // Your API key here
dangerouslyAllowBrowser: true,
});

const data = {
max_tokens: 50, // Adjust as needed
model: "gpt-3.5-turbo",
messages: [{ role: "user", content: userInput }],
};

const config = {
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${apiKey}`,
},
};

const generateResponse = async () => {
setTyping(true);

axios
.post(apiUrl, data, config)
.then((response) => {
response.data.choices.forEach((choice) => {
setResponse(choice.message.content);
});
})
.catch((error) => {
console.error("Error generating response", error);
})
.finally(() => {
setTyping(false);
});
};

return (
<div className="ad-container">
<h1 className="ad-title">Moon Highway Ad Generator</h1>
<textarea
className="ad-textarea"
value={userInput}
onChange={handleUserInput}
placeholder="Enter your prompt here"
/>
<button className="ad-button" onClick={generateResponse}>
Generate Response
</button>
{typing && <p>Typing...</p>}
{response && (
<div>
<h3>Generated Ad:</h3>
<p>{response}</p>
</div>
)}
</div>
);
};

export default AdComponent;

7. Run your app

npm start

Other Considerations

As web developers, it is our job to make places on the web not only aesthetically pleasing to our users or customers but also accessible. You may be aware of the increasing prominence of accessibility in design making content available for everyone. Introducing AI into our practices, we must also keep up to date on ethical considerations too. How can we train models that are not biased by prompts we wrote? How do we keep the playing field level in advancements if one group is developing it? What about the actual human element of just being a human? These are all things and questions that continue to evolve and things to consider as AI advances.

Tools and Resources to Keep Learning

There are many other resources, learning materials, and things out there for information about AI, even ask ChatGPT. The best way to get involved is to not run away from it but to try it out in your own projects like our chef would try a new recipe with some new ingredients.

Below are some projects to continue to learn and utilize AI in your projects.