Last active
April 29, 2022 23:21
-
-
Save aliyeysides/e284792ee5251ba32855cfca49fb1ab0 to your computer and use it in GitHub Desktop.
OpenAI JS content filter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Configuration, OpenAIApi } from "openai"; | |
const configuration = new Configuration({ | |
apiKey: process.env.OPENAI_API_KEY, | |
}); | |
const openai = new OpenAIApi(configuration); | |
async function contentFilter(prompt) { | |
const toxic_threshold = -0.355; // make sure required threshold hasn't changed https://beta.openai.com/docs/engines/content-filter | |
const wrappedPrompt = `<|endoftext|>${prompt}\n--\nLabel:`; | |
const response = await openai.createCompletion("content-filter-alpha", { | |
prompt: wrappedPrompt, | |
temperature: 0, | |
max_tokens: 1, | |
top_p: 0, | |
logprobs: 10, | |
}); | |
let output_label = response.data.choices[0].text; | |
if (output_label == "2") { | |
const logprobs = response.data.choices[0]["logprobs"]["top_logprobs"][0]; | |
if (logprobs["2"] < toxic_threshold) { | |
const logprob_0 = logprobs["0"]; | |
const logprob_1 = logprobs["1"]; | |
if (logprob_0 && logprob_1) { | |
if (logprob_0 >= logprob_1) { | |
output_label = "0"; | |
} else { | |
output_label = "1"; | |
} | |
} | |
if (logprob_0 && !logprob_1) { | |
output_label = "0"; | |
} | |
if (!logprob_0 && logprob_1){ | |
output_label = "1"; | |
} | |
} | |
} | |
if (!["0", "1", "2"].includes(output_label)) { | |
output_label = "2"; | |
} | |
return output_label; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment