Introduction to Arcjet content moderation for SvelteKit
Arcjet content moderation evaluates untrusted text for harmful content before it is stored, displayed, or forwarded to another service. Use it on user messages, tool-call results, and model outputs at the same action boundary as Agent guards.
What is Arcjet?
Arcjet is the AI agent runtime security platform. Discover the agents running in your organization, enforce policy across every action, prompt, and tool call, and keep the evidence to prove what happened. Detect prompt injection, authorize agent tool calls, redact PII, and block bots and abuse.Content moderation is a Guard rule. There is no protect() / HTTP-request
variant. Call it from guard() in JavaScript or Python, or Guard in Go.
When to use content moderation
Section titled “When to use content moderation”Use content moderation when you need a decision on text that is about to leave your control or be shown to a user, for example:
- User-facing chat and support assistants – block harmful messages before they are stored or displayed.
- Agent tool results and model outputs – scan generated text before it is forwarded to another tool, a customer, or a third-party API.
- Moderation at the action boundary – the same
guard()call can combine content moderation with rate limiting or prompt injection detection.
Content moderation answers a different question from prompt injection detection (hostile instructions aimed at the model) and sensitive information detection (PII and other regulated data). Combine them when a single untrusted string needs more than one check.
How Arcjet content moderation works
Section titled “How Arcjet content moderation works”- You configure
moderateContent()(JavaScript),ModerateContent()(Python), orGuardModerateContent(Go) once and reuse the rule. - At the action boundary, bind the untrusted text and submit it with
guard()/Guard. - Arcjet returns
ALLOWorDENY. A denial has reasonMODERATE_CONTENT. - The per-rule result is a
detected/Detectedverdict, the categories that fired, and optional billing intext_units.
The result lists which categories fired as detectedCategories (JavaScript),
detected_categories (Python), or DetectedCategories (Go):
SEXUALLY_EXPLICIT, MISCONDUCT, HATE_SPEECH, and INSULTS. Arcjet may
add categories later, so treat an unrecognized value as harmful content of an
unknown kind. Categories arrive in a fixed order, not by score. Scores and
thresholds are never returned. Treat detected / Detected as authoritative:
the list can be empty even when harmful content was detected, for example from
an older Arcjet server.
For what the default policy enforces and why it focuses on sexual content for payment processor compliance, see the content moderation policy.
SDK availability
Section titled “SDK availability”| SDK | Public API | Notes |
|---|---|---|
| JavaScript / TypeScript | moderateContent() | mode is optional and defaults to LIVE. |
| Python | ModerateContent() | mode is optional and defaults to LIVE. |
| Go | GuardModerateContent | Mode is required (ModeLive or ModeDryRun). An empty Mode returns ErrInvalidMode. |
Examples
Section titled “Examples”Configure the rule once, bind the untrusted text, and submit it with
guard() / Guard:
import { launchArcjet, moderateContent } from "@arcjet/guard";
const arcjet = launchArcjet({ key: process.env.ARCJET_KEY! });const moderate = moderateContent();
const decision = await arcjet.guard({ label: "tools.chat", rules: [moderate(userMessage)],});
if (decision.reason === "ERROR" || decision.hasFailedOpen()) { console.warn("Moderation did not complete", decision.id, decision.errorResults().map((result) => result.code)); throw new Error("Content check could not complete");}if (decision.conclusion !== "ALLOW") { throw new Error("Message blocked by policy");}
const result = moderate.result(decision);// `detected` is true when harmful content was found. Billing is undefined// when the service does not report usage. Content moderation uses text_units.console.log(result?.detected, result?.billing?.unit, result?.billing?.count);// `detectedCategories` names what was found, such as "HATE_SPEECH" or// "INSULTS". Decide on `detected`: the list can be empty even when it is true.console.log(result?.detectedCategories);import os
from arcjet.guard import ModerateContent, launch_arcjet
arcjet = launch_arcjet(key=os.environ["ARCJET_KEY"])moderate = ModerateContent()
decision = await arcjet.guard( label="llm.output", rules=[moderate(text)],)
if decision.reason == "ERROR" or decision.has_failed_open(): raise RuntimeError("Content check could not complete")if decision.conclusion != "ALLOW": raise RuntimeError("Message blocked by policy")
result = moderate.result(decision)# `detected` is True when harmful content was found. Billing is None# when the service does not report usage. Content moderation uses text_units.print(result.detected if result else None)# `detected_categories` names what was found, such as "HATE_SPEECH" or# "INSULTS". Decide on `detected`: the tuple can be empty even when it is True.print(result.detected_categories if result else ())if result and result.billing: print(result.billing.unit, result.billing.count)moderation, err := arcjet.GuardModerateContent(arcjet.GuardModerateContentOptions{ Mode: arcjet.ModeLive, // required})if err != nil { return err}
decision, err := guard.Guard(ctx, arcjet.GuardRequest{ Label: "tools.generate", Rules: []arcjet.GuardRuleInput{moderation.Text(userMessage)},})if err != nil { return err}// Deny harmful content, text over 128 KiB, and checks that Arcjet couldn't// complete. Arcjet moderates the first 60 KB and adds an AJ1142 warning to// decision.Warnings for longer text. To moderate all of it, split it up.if decision.HasFailedOpen() || decision.Reason == arcjet.ReasonError { return errors.New("content check could not complete")}if !decision.IsAllowed() { return errors.New("message blocked by policy")}if moderation.Result(decision) == nil { return errors.New("missing content moderation verdict")}
if result := moderation.Result(decision); result != nil { // DetectedCategories names what was found, such as HATE_SPEECH or // INSULTS. Decide on Detected: the list can be empty even when it is true. fmt.Printf("detected=%v categories=%v\n", result.Detected, result.DetectedCategories) // Billing is optional. Content moderation usage is measured in text_units. if result.Billing != nil { fmt.Printf("charged %d %s\n", result.Billing.Count, result.Billing.Unit) }}Set Mode on every Guard rule. An empty Mode returns ErrInvalidMode.
For install steps and framework-specific wrappers, see the content moderation quick start.
Dry run mode
Section titled “Dry run mode”mode: "DRY_RUN" / ModeDryRun evaluates the rule without blocking. Use this
to measure detections before switching to "LIVE".
Errors and timeouts
Section titled “Errors and timeouts”A moderation denial tells your application that policy blocked the message.
When a required live check fails to finish, Guard also returns DENY, with
reason ERROR. In either case, stop before storing or forwarding the text.
The error results help you decide whether the caller should retry or correct
the input. Use errorResults() in JavaScript, error_results() in Python,
and ErrorResults() in Go. Go can also return a Go error alongside the
decision.
Moderation reads the first 60 KB of a message. Longer text produces
warning AJ1142, and the rest of the message goes unchecked. If you need to
check the entire message, split it into parts and wait for an allow for each
part before using the text. Inputs over 128 KiB are rejected in live mode
and produce an error in dry run.
See Guard failure handling for the SDK versions that enforce this behavior and for wrapper options.
Data handling
Section titled “Data handling”Content moderation runs on Arcjet, so the text that you pass to the rule is sent to the Arcjet Cloud API for evaluation. Arcjet doesn’t store the text. The decision keeps the verdict, the billing count, and the label and metadata that you attach to the call, so don’t copy the text into metadata. For what else Arcjet stores and for how long, see Arcjet privacy.
Pricing
Section titled “Pricing”Content moderation is priced based on usage, measured in text_units when the
service reports billing. A text unit is the length of the text you submit to a
single moderation call, in characters, divided by 1,000 and rounded up. For a
worked example, see how
text units are calculated. For the price per text unit, see the
pricing page.