How to implement the GPT-3's Content filter in Node.js / JavaScript

Introduction

OpenAI provides a content filter API that can be used to filter out unwanted content from the text generated through their AI models.

In fact, OpenAI makes it mandatory to run every response through content filter in your GPT-3 application or product before you can release it to the public.

In this short tutorial, I am going to show you how to use the content filter API to filter out unwanted content from the text generated by GPT-3 in your Node.js or JavaScript application.

Implementing the content filter

Main idea is you need to take the the output from the text generation API call and send it to the content API endpoint, that uses the OpenAI’S content filter engine. And then you need to parse the content label you received and make the decision to show the content to end user or not.

let’s look at it the code.

Let’s say you genearted some content via OpenAI GPT-3 API endpoints

const content_to_classify = 'This content was generated by GPT-3';

You will then pass this along to the content filter API endpoint along with some paramters, like this.

const filterResponse = await openai.complete({
    engine: "content-filter-alpha-c4",
    prompt: "< endoftext|>" + content_to_classify + "\n--\nLabel:",
    temperature: 0,
    maxTokens: 1,
    topp: 1,
    frequencyPenalty: 0,
    presencePenalty: 0,
    logprobs: 10,
})

Once you have the response, you need to parse the content label you received.

const filterLabel = filterResponse.data.choices[0].text

OpenAI recommends that If the labels is as 1 or 2, you go ahead and show it to the user. Otherwise, you need to reject that output or do more checks on the generated content before you can display it to the user. As demonstrated in this code.

if (filterLabel == "0" || filterLabel == "1" ) {
    res.status(200).json({
        text: '${content_to_classify}' })
}
else {
    res.status(200).json({ text: "Try again, after modifying the prompt." })
}

Conclusion

In this post, I have shown you how to use the content filter API to filter out unwanted content from the text generated by GPT-3 in your Node.js or JavaScript application.