Build an AI-powered Business Name Generator with Google AI

Build an AI-powered Business Name Generator with Google AI

In this blog post, we'll create an AI-powered business name generator using Google AI Platform's Text-to-Text Generation API, Node.js for the backend, and React.js for the front-end.

Backend with Node.js

The backend handles communication with Google Generative AI's API and processes user input to generate business names. Here's a breakdown of the key components:

  1. Dependencies:

    • @google-ai/generativelanguage: interacts with the Google AI Platform Text-to-Text Generation API.

    • google-auth-library: authenticates with Google Cloud Platform.

    • dotenv: manages environment variables securely (stores your Google API key).

    • express: a lightweight web framework for Node.js.

    • body-parser: parses incoming request bodies (user input).

    • cors: enables Cross-Origin Resource Sharing (CORS) for front-end communication.

  2. Obtain an API Key:

  3. API Endpoint:

    • The /generate-names endpoint is a POST request handler that receives user input from the frontend and performs the following actions:

      1. Retrieves user input: It extracts the category, keywords, and desired name length from the request body.

      2. Constructs a prompt: Based on the user input, it crafts a specific prompt that guides the AI model towards generating relevant business names. For example, the prompt might be: "Generate unique, memorable and catchy business names related to [category] with the help of keywords like [keywords] with maximum character limit up to [length] characters."

      3. Calls the Text-to-Text Generation API: Using Google AI's API key, the backend sends the constructed prompt to the Text-to-Text Generation API for processing.

      4. Processes the API response: The API response contains the generated names. The backend extracts these names and performs basic cleaning to remove special characters and empty strings.

      5. Sends the results back: Finally, the cleaned list of business names is sent back to the front-end as a JSON response.

Here's a glimpse of the core backend code (remember to replace <YOUR_API_KEY> with your actual key):

    const MODEL_NAME = "models/text-bison-001";
    const API_KEY = process.env.GOOGLE_API_KEY || '<YOUR_API_KEY>';

    const client = new TextServiceClient({
      authClient: new GoogleAuth().fromAPIKey(API_KEY),
    });

    // Endpoint to generate business names based on user input
    app.post("/generate-names", async (req, res) => {
      try {
        const { category, keywords, length } = req.body;

        console.log("Sending data to API:", {
          category: category,
          keywords: keywords,
          length: length,
        });

        // Construct prompt based on user input
        const prompt = `Generate unique, memorable and catchy business names related to ${category} with the help of keywords like ${keywords} with maximum character limit upto ${length} characters.`;

        // Call Google AI Platform Text-to-Text Generation API
        const response = await client.generateText({
          model: MODEL_NAME,
          prompt: {
            text: prompt,
          },
        });

Frontend with React.js

The front-end provides a user-friendly interface for interacting with the AI name generator. Here are the key functionalities:

  1. Components:

    • NamenGen component manages the overall application state and logic.

    • State variables hold user input (category, keywords, and desired name length) and the generated names.

    • A handleGenerateNames function is triggered when the user clicks the "Generate" button.

    • This function sends user input to the backend API using Axios and handles the response.

    • Conditional rendering displays loading animations while names are being generated and display the generated names in styled boxes.

  2. User Interface:

    • The UI consists of a banner with a captivating message highlighting the importance of a good business name.

    • Input fields allow users to specify the business category, relevant keywords, and desired name length.

    • A button triggers the name-generation process.

    • The generated names are displayed in visually appealing boxes.

  3. Main part of the code:

     const handleGenerateNames = async () => {
         setIsLoading(true);
         try {
           // Check if category, keywords, and length are provided
           const response = await axios.post(
             "http://localhost:5000/generate-names",
             {
               category: category,
               keywords: keywords,
               length: length,
             },
             {
               headers: {
                 "Content-Type": "application/json",
               },
             }
           );
           console.log(response);
    
           // Assuming the names are separated by new lines
           const rawNames = response.data.names;
    
           // Filter out any lines that don't match the expected format of a name
           // This is a basic example; you might need to adjust the condition based on the actual format of the names
           const cleanedNames = rawNames.filter((name) =>
             name.match(/^[A-Za-z0-9\s]+$/)
           );
    
           // Clean up names by removing all digits and dots
           const newCleanedNames = cleanedNames.map((name) =>
             name.replace(/\d+|\./g, "")
           );
    
           // Now `cleanedNames` contains only the names, without any extra sentences
           setGeneratedNames(newCleanedNames);
         } catch (error) {
           console.error("Error generating names:", error);
         } finally {
           setIsLoading(false); // Reset loading state to false after fetching data
         }
       };
    

Putting it All Together

Once you have developed both the backend and frontend components, deploy them to a suitable hosting platform. Finally, configure your front-end to make requests to the backend API endpoint.

This AI-powered business name generator empowers users to overcome creative roadblocks and explore a wider range of naming possibilities. With the help of Google AI and modern web development frameworks, you can create a valuable tool for entrepreneurs and businesses.

Here's the Entire Code:

App.js:

import { v1beta2 } from "@google-ai/generativelanguage";
const { TextServiceClient } = v1beta2;
import { GoogleAuth } from "google-auth-library";
import dotenv from "dotenv";
import express from "express";
import bodyParser from "body-parser";
import cors from "cors";

dotenv.config();

const app = express();
const port = process.env.PORT || 5000;

// Middleware for parsing JSON bodies
app.use(bodyParser.json());


app.use(cors());

const MODEL_NAME = "models/text-bison-001";
const API_KEY = process.env.GOOGLE_API_KEY;

const client = new TextServiceClient({
  authClient: new GoogleAuth().fromAPIKey(API_KEY),
});

// Endpoint to generate business names based on user input
app.post("/generate-names", async (req, res) => {
  try {
    const { category, keywords, length } = req.body;

    console.log("Sending data to API:", {
      category: category,
      keywords: keywords,
      length: length,
    });

    // Construct prompt based on user input
    const prompt = `Generate unique, memorable and catchy business names related to ${category} with the help of keywords like ${keywords} with maximum character limit upto ${length} characters.`;

    // Call Google AI Platform Text-to-Text Generation API
    const response = await client.generateText({
      model: MODEL_NAME,
      prompt: {
        text: prompt,
      },
    });

    console.log("API Response: ", JSON.stringify(response, null, 2));
    let output = response[0].candidates[0].output;
    console.log(output);

    // Assuming the names are separated by commas
    const generatedNames = output.split("\n");

    // Remove special characters from each name
    const cleanedNames = generatedNames.map((name) =>
      name.replace(/[^a-zA-Z0-9 ]/g, "").trim()
    );

    // Remove any empty strings from the array
    const filteredNames = cleanedNames.filter((name) => name !== "");

    // Send cleaned names array to frontend
    res.json({ names: filteredNames });
  } catch (error) {
    console.error("Error generating business names:", error);
    res
      .status(500)
      .json({ error: "An error occurred while generating business names." });
  }
});

// Start the server
app.listen(port, () => {
  console.log(`Server is running on http://localhost:${port}`);
});

NameGen.jsx:

import React, { useState, useEffect } from 'react';
import axios from 'axios';

const NameGen = () => {
  const [category, setCategory] = useState('');
  const [keywords, setKeywords] = useState('');
  const [length, setLength] = useState(0);
  const [generatedNames, setGeneratedNames] = useState([]);
  const [isLoading, setIsLoading] = useState(false);

  const handleGenerateNames = async () => {
    setIsLoading(true);
    try {
      const response = await axios.post(
        "http://localhost:5000/generate-names", // Replace with your backend API endpoint URL
        {
          category,
          keywords,
          length,
        },
        {
          headers: {
            "Content-Type": "application/json",
          },
        }
      );
      setGeneratedNames(response.data.names);
    } catch (error) {
      console.error("Error generating names:", error);
      // Handle errors appropriately (e.g., display an error message to the user)
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <div className="name-generator">
      <h1>Generate Creative Business Names</h1>
      <div className="input-fields">
        <label htmlFor="category">Category:</label>
        <input
          type="text"
          id="category"
          value={category}
          onChange={(e) => setCategory(e.target.value)}
        />
        <label htmlFor="keywords">Keywords:</label>
        <input
          type="text"
          id="keywords"
          value={keywords}
          onChange={(e) => setKeywords(e.target.value)}
        />
        <label htmlFor="length">Desired Name Length:</label>
        <input
          type="number"
          id="length"
          value={length}
          onChange={(e) => setLength(parseInt(e.target.value))}
        />
      </div>
      <button onClick={handleGenerateNames} disabled={isLoading}>
        {isLoading ? 'Generating...' : 'Generate Names'}
      </button>
      {generatedNames.length > 0 && (
        <div className="generated-names">
          <h2>Generated Names:</h2>
          <ul>
            {generatedNames.map((name) => (
              <li key={name}>{name}</li>
            ))}
          </ul>
        </div>
      )}
    </div>
  );
};

export default NameGen;

By leveraging the power of Google AI and modern web development frameworks, you can create an innovative tool that streamlines business naming and sparks creative thinking for entrepreneurs and businesses. Want to generate catchy business names instantly? Head over to my business name generator here.

Happy Coding!