Saltar al contenido

Lección 21 · Safety and Production

Safety and Moderation

Protect your OpenAI app with the free moderation endpoint, safety identifiers, input limits, prompt injection defenses, human review and user reporting.

When you put a model into an app, people will use it in ways you did not plan. Some will be curious, some careless and a few will try to make it misbehave. Safety is not one filter. It is several layers: limits on input, checks on content, restrictions on actions and people who can step in.

OpenAI's usage policies apply to your application. Read them before you launch, because you are responsible for how your product uses the API.

Layers of protection

Defense in layers

Input limits Size, rate, sign-in
Content checks Moderation and rules
Action limits Permissions, approvals
People Review and reporting

No single layer catches everything.

1 / 2

The moderation endpoint

OpenAI offers a moderation endpoint that classifies content into categories such as harassment, hate, self-harm, sexual content and violence. The moderation guide says it is free to use. As of December 2026, the model ID is omni-moderation-latest. It accepts text and images (not audio).

Python
# Read-only
result = client.moderations.create(
    model="omni-moderation-latest",
    input="Text from a user goes here.",
)

item = result.results[0]
print(item.flagged)
print(item.categories)
print(item.category_scores)

Some categories apply only to text. If you send only an image, those categories score zero, so do not read a zero as "checked and safe."

You can also request moderation inside a response by passing moderation={"model": "omni-moderation-latest"}. The response then contains separate results for input and output. Check whether either one reports an error before you read scores. With streaming, these scores arrive only after the full output exists.

Turn scores into decisions

A score is a signal, not a decision. Your policy chooses the action: allow, warn, hold for review or block. Different categories need different thresholds. The numbers below are invented to show the logic. Choose your own by testing labeled examples from your domain.

Python Stand-in: a moderation policy

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Two design choices are worth copying. A missing score leads to review, not to approval. And a possible self-harm message gets a helpful response path: show appropriate support resources and a way to reach a person, instead of only a block message.

Moderation can be wrong in both directions. It may flag a harmless discussion of a safety topic, or miss harmful content. A refusal that discusses a harmful topic may be flagged too.

Safety identifiers

OpenAI asks you to send a safety identifier: a stable ID for each end user. It helps OpenAI detect abuse and helps you respond. Do not send names or email addresses. Send a hash.

Python
import hashlib
import hmac

def safety_id(user_id: str, secret: bytes) -> str:
    return hmac.new(secret, user_id.encode(), hashlib.sha256).hexdigest()

Pass it as safety_identifier in Responses and Chat Completions, and in image requests. For Realtime, send it in the OpenAI-Safety-Identifier header from your server. It does not carry over between APIs or sessions, so send it each time. For visitors who are not signed in, a session ID works.

Limit what users can send and do

OpenAI's safety guidance recommends controls such as these:

  • Require sign-in where abuse would matter.
  • Cap input length and output tokens.
  • Prefer fixed choices over free text when you can.
  • Rate-limit each user.
  • Test with adversarial input (red teaming).
  • Give users a way to report problems, and have people respond.
  • Tell users about the app's limits.

Prompt injection

Prompt injection is when text, typed by a user or hidden in a web page, email or file, tries to change what the model does. No prompt wording stops it completely. Design as if it may succeed:

  • Give the model only the data this user may see.
  • Give it only the tools the task needs, with permission checks in code.
  • Require approval for actions with real effects.
  • Do not let model output run as code or SQL.
  • Block output that could leak data, such as automatically loading external image links.

Study prompt injection and security and guardrails for agents.

High-stakes uses

For health, law, money, hiring or safety decisions, mistakes can seriously harm people. Keep qualified humans in charge, give reviewers the source material, and check the laws and policies that apply. Do not present model output as professional advice.

When something goes wrong

Prepare before it happens: a way to disable a feature quickly, logs that let you investigate while respecting privacy, a person who is on call, and a plan to revoke keys. Turn each incident into a test case.

Do not show your internal moderation thresholds or detailed reasons for a block to users who are probing the system. Give a polite, clear message and a way to appeal.

Test your safety layers

Safety measures need tests like any other feature. Build a small set of examples that should be allowed, reviewed and blocked, including borderline and harmless-but-sensitive cases, such as a question about medicine safety. Measure both mistakes: harmful content that passes, and normal users who are blocked. Include the languages your users write in, because results may differ between them. Handle disturbing test material carefully, keep access limited and do not ask staff to read more of it than needed.

Decide what happens when the moderation call itself fails. For a public posting feature, holding content for review is usually safer than publishing it unchecked.

Common mistakes

  • Checking user input but never checking what the model sends back.
  • Using one threshold for every category without testing it.
  • Offering a report button when nobody is assigned to read the reports.

Review these examples again whenever you change your policy, your model or your product, and record who approved each threshold and why, so later changes are deliberate.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. What is a moderation score?

    Your application chooses what to do with scores.
  2. 2. What should a safety identifier contain?

    It identifies a user without sending identifying information.
  3. 3. Which approach to prompt injection is soundest?

    Design so that a successful injection can do little damage.
  4. 4. An image-only moderation request shows 0 for a text-only category. What does that mean?

    Text-only categories return zero for image-only input.

Summary

  • Combine input limits, content checks, action limits and human oversight.
  • Use the moderation endpoint and set policies by testing your own data.
  • Send hashed safety identifiers.
  • Assume prompt injection can succeed and limit its effect.
  • Keep humans in charge of high-stakes decisions and prepare for incidents.

Next: Testing and Evaluating

Tu progreso se guarda en este navegador. No necesitas una cuenta.