Create moderation

Classifies if text is potentially harmful.

Script openai Verified

by adam186 ยท 12/12/2022

The script

Submitted by hugo697 Typescript (fetch-only)
Verified 372 days ago
1
type Openai = {
2
  api_key: string;
3
  organization_id: string;
4
};
5
/**
6
 * Create moderation
7
 * Classifies if text is potentially harmful.
8
 */
9
export async function main(
10
  auth: Openai,
11
  body: {
12
    input: string | string[];
13
    model?: string | ("text-moderation-latest" | "text-moderation-stable");
14
    [k: string]: unknown;
15
  }
16
) {
17
  const url = new URL(`https://api.openai.com/v1/moderations`);
18

19
  const response = await fetch(url, {
20
    method: "POST",
21
    headers: {
22
      "OpenAI-Organization": auth.organization_id,
23
      "Content-Type": "application/json",
24
      Authorization: "Bearer " + auth.api_key,
25
    },
26
    body: JSON.stringify(body),
27
  });
28
  if (!response.ok) {
29
    const text = await response.text();
30
    throw new Error(`${response.status} ${text}`);
31
  }
32
  return await response.json();
33
}
34

Other submissions
  • Submitted by adam186 Deno
    Created 1004 days ago
    1
    import { Configuration, OpenAIApi } from "npm:[email protected]";
    2
    
    
    3
    type Openai = {
    4
      api_key: string;
    5
      organization_id: string;
    6
    };
    7
    export async function main(
    8
      auth: Openai,
    9
      prompt: string,
    10
      model:
    11
        | "text-moderation-latest"
    12
        | "text-moderation-stable" = "text-moderation-latest",
    13
    ) {
    14
      const configuration = new Configuration({
    15
        apiKey: auth.api_key,
    16
        organization: auth.organization_id,
    17
      });
    18
      const openai = new OpenAIApi(configuration);
    19
    
    
    20
      const response = await openai.createModeration({
    21
        input: prompt,
    22
        model,
    23
      });
    24
      return response.data;
    25
    }
    26