Module 4, Lesson 2: The Moderation API
Call OpenAI's free Moderation API, read what comes back and see why it judges harm and not topic.
Published: 11/27/2026
The Moderation API takes a piece of text and says whether it contains harmful content. It is a plain web service, not a chat model, and it is free.
1. The call
import OpenAI from "openai"; const client = new OpenAI(); const response = await client.moderations.create({ model: "omni-moderation-latest", input: "I will hurt you and everyone in this hotel", });
There is no system prompt and no conversation. You send one string and get a verdict back.
2. What comes back
Here is the real response for that message, shortened. The real one lists all 13 categories, cuts the scores to the three highest here, and has one extra field (category_applied_input_types) that is left out.
{ "id": "modr-5815", "model": "omni-moderation-latest", "results": [ { "flagged": true, "categories": { "harassment": true, "harassment/threatening": true, "hate": false, "illicit": false, "violence": true, "violence/graphic": false }, "category_scores": { "violence": 0.9354814381798597, "harassment/threatening": 0.5311878304975104, "harassment": 0.5267091791797128 } } ] }
| Field | Meaning |
|---|---|
results | One item per input. You sent one string, so you read results[0]. |
flagged | true if any category is flagged. This is the field the chat acts on. |
categories | True or false for each category. OpenAI decides which are true. |
category_scores | A number from 0 to 1 per category. Higher means more likely. |
There are 13 categories, such as harassment, hate, illicit (asking for help with a crime), self-harm, sexual and violence. Some have sub-types, like harassment/threatening.
A message can have a middling score and still not be flagged. OpenAI decides when a score is high enough, and it doesn't tell you where that line is, so use flagged.
3. Three samples side by side
| Message | flagged | Flagged categories |
|---|---|---|
| "Plan 5 days in Lisbon in May" | false | none |
| "What is 17 times 23?" | false | none |
| "I will hurt you and everyone in this hotel" | true | harassment, harassment/threatening, violence |
The maths question is as clean as the travel question. Moderation judges harm, not topic. It has no idea that your assistant is about travel, so it waves through anything that isn't harmful. That is why Module 3's guardrail is still needed.
4. Three small functions
The playground keeps the call and the summary apart, so the raw output can be shown. Create src/openai/input-moderation.ts with these three functions, plus the imports and a small result type.
import dotenv from "dotenv"; import OpenAI from "openai"; import type { ModerationCreateResponse } from "openai/resources/moderations"; dotenv.config({ quiet: true }); export const moderationModel = "omni-moderation-latest"; export type ModerationResult = { /** true when the message should be blocked */ flagged: boolean; /** One short sentence, in the same style as the guardrail's reason */ reason: string; model: string; /** Categories that were flagged, e.g. ["harassment", "violence"] */ categories: string[]; }; // Created on first use so importing this file never needs an API key let client: OpenAI | undefined; /** The Moderation API call. Throws if it fails (callers decide what to do). */ export const moderate = async (text: string): Promise<ModerationCreateResponse> => { client ??= new OpenAI(); return client.moderations.create({ model: moderationModel, input: text }); };
moderate is just the call. It throws if the call fails, and the caller decides what to do about it.
/** Reduces the raw response to a block/allow decision and a reason. */ export const summariseModeration = (response: ModerationCreateResponse): ModerationResult => { // One input string in, so one result out const result = response.results[0]; if (!result) throw new Error("moderation returned no result"); const categories = Object.entries(result.categories) .filter(([, hit]) => hit) .map(([name]) => name); return { flagged: result.flagged, reason: result.flagged ? `Flagged by moderation: ${categories.join(", ")}.` : "No moderation category was flagged.", model: response.model, categories, }; }; /** Checks `text`. Throws if the call fails (callers decide what to do). */ export const runInputModeration = async (text: string): Promise<ModerationResult> => summariseModeration(await moderate(text));
| Function | What it does |
|---|---|
moderate(text) | The API call. Returns OpenAI's raw response. |
summariseModeration(response) | Keeps only { flagged, reason, model, categories }. |
runInputModeration(text) | Both together. The chat and the test runner call this one. |
The summary has the same shape as the guardrail's verdict: a yes or no, and one sentence saying why. Both checks return that, so the chat in the next lesson can treat them the same way.
5. Try it
To see the output for yourself, create src/utils/show-input-moderation.ts. This is a minimal version.
import { moderate, summariseModeration } from "../openai/input-moderation.js"; const text = process.argv[2] ?? "Plan 5 days in Lisbon in May"; const response = await moderate(text); console.log(JSON.stringify(response, null, 2)); console.log(JSON.stringify(summariseModeration(response), null, 2));
pnpm tsx src/utils/show-input-moderation.ts "some message"
It prints the raw response, then the summary. The playground's longer version of this script also tries three built-in samples, prints the request, and shortens the scores to the top three unless you pass --scores.
Try a travel question, a maths question and something rude. Only the harmful one is flagged, however off topic the others are.
👉 Continue to Lesson 3: Two checks in the chat