Generating tags/categories for a given sentence using Chat GPT API and Firebase Cloud Function

Generating tags/categories for a given sentence using Chat GPT API and Firebase Cloud Function

Generating topics for a given quote can be challenging, but with advancements in AI and natural language processing, now it's possible to generate topics with high accuracy. In this article, we'll go through how to use the Chat GPT API to generate topics for a given quote and host the method in the Firebase cloud function HTTP method.

What is Chat-GPT-API?

Chat-GPT-API is an API that provides access to OpenAI's GPT (Generative Pre-trained Transformer) language model. GPT is a machine learning model that is trained to generate human-like text based on a given prompt. The Chat-GPT-API allows developers to integrate the GPT model into their applications and generate text based on user input.

What are Firebase Cloud Functions?

Firebase Cloud Functions is a serverless compute service that allows developers to run code in response to events and automatically scale based on traffic. Firebase Cloud Functions supports Node.js, Python, Java, Go, and .NET. In this article, we will use Firebase Cloud Functions with Node.js to host our code.

Now that we have an understanding of the technologies we will be using, let's take a look at the process.

The first step in creating a tag/category is to create a list of topics from which to choose. In our example, we defined a list of default topics as an array of objects with an id and name field. Below is an example:

const defaultTags = [
    { id: "1", name: "Eat Healthy" },
    { id: "2", name: "Health and Wellness" },
    { id: "3", name: "Life/Lifestyle" },
    { id: "4", name: "entrepreneurship" },
    { id: "5", name: "wisdom" },
    { id: "6", name: "relationships" }
  ];        

Next, we need to set up the configuration for the OpenAI API using our API key.

const configuration = new Configuration({
  apiKey: process.env.OPENAI_API_KEY,
});        

The function that creates the topics can now be defined. We will host this function in Firebase cloud function HTTP way so that we may access it via an API endpoint.

exports.generateTopics = functions.https.onRequest(async (req, res) => 
? // Do something with the parsed body
? console.log("body:", req.body);
? var data = req.body;


? // Set up OpenAI API
? const openai = new OpenAIApi(configuration);


? // Create user prompt
? var tagNames = defaultTags.map((tag) => tag.name);
  // prompt to be fed into the chat-gpt-api
? var userPrompt =
? ? "Assign multiple topics as an array from the topic list given below to the following quote:\nQuote - " +
? ? data.content +
? ? "\n\ntopics = [" +
? ? tagNames.join(", ") +
? ? "]\n\n Output should be in the format `topics = ['']`";


? // Generate topics using OpenAI API
? const response = await openai.createChatCompletion({
? ? model: "gpt-3.5-turbo",
? ? messages: [
? ? ? { role: "system", content: "You are a helpful assistant." },
? ? ? { role: "user", content: userPrompt },
? ? ],
? ? temperature: 0.8,
? ? max_tokens: 150,
? ? top_p: 1,
? ? frequency_penalty: 0,
? ? presence_penalty: 0.6,
? });


? // Extract topics from generated string using regular expression
? const message = response.data.choices[0];
? const json = message.message;
? const content = JSON.stringify(json.content);
? const topicsArr = content
? ? .match(/\[([^[\]]*)\]/)[1]
? ? .match(/'[^']*'/g)
? ? .map((topic) => topic.slice(1, -1));
? const generatedTopics = topicsArr.map((str) => str.toLowerCase());


? // Match generated topics with default tags and create result object
? const updatedTags = defaultTags.map((tag) => ({
? ? ...tag,
? ? name: tag.name.toLowerCase(),
? }));
? const selectedTagObjects = updatedTags
? ? .filter((tag) => generatedTopics.includes(tag.name))
? ? .map(({ id, name }) => ({ id, name }));
? var result = {
? ? id: data.id,
? ? content: data.content,
? ? tags: selectedTagObjects,
? };


? // Send response
?cors(req,res, ()=>{
    res.status(200).json({result})
  })
  
})        

The `userPrompt` in the above code is a message that is sent to the OpenAI GPT-3 API to generate topics for a given quote.

var userPrompt =
? ? "Assign multiple topics as an array from the topic list given below to the following quote:\nQuote - " +
? ? data.content +
? ? "\n\ntopics = [" +
? ? tagNames.join(", ") +
? ? "]\n\n Output should be in the format `topics = ['']`";        

The prompt message consists of two parts:

  1. System message: This is a message that is sent by the system to the OpenAI API to indicate that the user is a helpful assistant.
  2. User message: This is a message that is sent by the user to the OpenAI API as a prompt for topic generation. The user message consists of the following parts:

  • The quote: This is the content for which the topics need to be generated.
  • The topic list: This is a list of default tags that are available for topic selection. The topic list is obtained from the defaultTags array defined in the code.
  • The output format: This is the format in which the generated topics need to be returned. In this case, it is specified as topics = [''].

In the above code, the regular expression is used to extract the topics from the generated string.

const topicsArr = str.match(/\[([^[\]]*)\]/)[1].match(/'[^']*'/g).map(topic => topic.slice(1, -1));        

then we can return the `topicsArr` in the response to be used in fronted.

var result = 
        "id": data.id,
        "content": data.content,
        "tags": selectedTagObjects
    }
    cors(req,res, ()=>{
        res.status(200).json({result})
    }){        


In conclusion, using the Chat GPT API for generating topics from a given quote can be a useful tool in various applications, such as content tagging and topic identification. The code snippet above demonstrates how we can utilize this API in a Firebase Cloud Function and provide an endpoint to generate topics from a given quote. By simply sending a post request with the quote in the request body, we can get back a list of relevant topics generated by the API. This can be further improved and integrated with other systems to create a more comprehensive solution for content analysis and classification.

要查看或添加评论,请登录

社区洞察

其他会员也浏览了