---
title: Inhaltsmoderation
url: https://platform.claude.com/docs/de/about-claude/use-case-guides/content-moderation
description: Inhaltsmoderation ist ein entscheidender Aspekt, um in digitalen Anwendungen eine sichere, respektvolle und produktive Umgebung aufrechtzuerhalten. Dieser Leitfaden erläutert, wie Claude zur Moderation von Inhalten in deiner digitalen Anwendung eingesetzt werden kann.
---

> Besuche das [Cookbook zur Inhaltsmoderation](https://platform.claude.com/cookbook/misc-building-moderation-filter), um eine Beispielimplementierung für Inhaltsmoderation mit Claude zu sehen.

<Tip>
  Dieser Leitfaden konzentriert sich auf die Moderation nutzergenerierter Inhalte innerhalb deiner Anwendung. Wenn du nach Anleitungen zur Moderation von Interaktionen mit Claude suchst, lies 

  [Jailbreaks und Prompt-Injections abschwächen](https://platform.claude.com/docs/de/test-and-evaluate/strengthen-guardrails/mitigate-jailbreaks)

  .
</Tip>

## Vor dem Entwickeln mit Claude

### Entscheide, ob du Claude für die Inhaltsmoderation verwenden möchtest

Hier sind einige wichtige Indikatoren dafür, dass du ein „large language model“ (großes Sprachmodell), oder LLM, wie Claude anstelle eines traditionellen ML- oder regelbasierten Ansatzes für die Inhaltsmoderation verwenden solltest:

<AccordionGroup>
  <Accordion title="Du möchtest eine kostengünstige und schnelle Implementierung">
    Traditionelle ML-Methoden erfordern erhebliche Engineering-Ressourcen, ML-Expertise und Infrastrukturkosten. Menschliche Moderationssysteme verursachen noch höhere Kosten. Mit Claude kannst du ein ausgefeiltes Moderationssystem in deutlich kürzerer Zeit und zu wesentlich geringeren Kosten in Betrieb nehmen.
  </Accordion>

  <Accordion title="Du möchtest sowohl semantisches Verständnis als auch schnelle Entscheidungen">
    Traditionelle ML-Ansätze wie Bag-of-Words-Modelle oder einfaches Pattern-Matching haben oft Schwierigkeiten, den Ton, die Absicht und den Kontext von Inhalten zu verstehen. Menschliche Moderationssysteme sind zwar hervorragend darin, semantische Bedeutung zu erfassen, benötigen aber Zeit für die Überprüfung der Inhalte. Claude erfüllt beide Anforderungen, indem es semantisches Verständnis mit der Fähigkeit kombiniert, Moderationsentscheidungen schnell zu liefern.
  </Accordion>

  <Accordion title="Du benötigst konsistente Richtlinienentscheidungen">
    Durch die Nutzung seiner fortgeschrittenen Reasoning-Fähigkeiten kann Claude komplexe Moderationsrichtlinien einheitlich interpretieren und anwenden. Diese Konsistenz trägt dazu bei, eine faire Behandlung aller Inhalte sicherzustellen, und verringert das Risiko inkonsistenter oder voreingenommener Moderationsentscheidungen, die das Vertrauen der Nutzer untergraben können.
  </Accordion>

  <Accordion title="Deine Moderationsrichtlinien werden sich wahrscheinlich im Laufe der Zeit ändern oder weiterentwickeln">
    Sobald ein traditioneller ML-Ansatz etabliert ist, ist seine Änderung ein mühsames und datenintensives Unterfangen. Claude hingegen kann sich, wenn sich dein Produkt oder die Bedürfnisse deiner Kunden weiterentwickeln, problemlos an Änderungen oder Ergänzungen der Moderationsrichtlinien anpassen, ohne dass Trainingsdaten umfangreich neu gelabelt werden müssen.
  </Accordion>

  <Accordion title="Du benötigst nachvollziehbare Begründungen für deine Moderationsentscheidungen">
    Wenn du Nutzern oder Regulierungsbehörden klare Erklärungen für Moderationsentscheidungen liefern möchtest, kann Claude detaillierte und kohärente Begründungen generieren. Diese Transparenz ist wichtig, um Vertrauen aufzubauen und Rechenschaftspflicht bei Praktiken der Inhaltsmoderation sicherzustellen.
  </Accordion>

  <Accordion title="Du benötigst mehrsprachige Unterstützung, ohne separate Modelle pflegen zu müssen">
    Traditionelle ML-Ansätze erfordern in der Regel separate Modelle oder umfangreiche Übersetzungsprozesse für jede unterstützte Sprache. Menschliche Moderation erfordert die Einstellung von Personal, das jede unterstützte Sprache fließend beherrscht. Claudes mehrsprachige Fähigkeiten ermöglichen es, Tickets in verschiedenen Sprachen zu klassifizieren, ohne dass separate Modelle oder umfangreiche Übersetzungsprozesse erforderlich sind, was die Moderation für globale Kundenstämme vereinfacht.
  </Accordion>

  <Accordion title="Du benötigst multimodale Unterstützung">
    Claudes multimodale Fähigkeiten ermöglichen es, Inhalte sowohl in Text- als auch in Bildform zu analysieren und zu interpretieren. Das macht Claude zu einem vielseitigen Tool für umfassende Inhaltsmoderation in Umgebungen, in denen verschiedene Medientypen gemeinsam bewertet werden müssen.
  </Accordion>
</AccordionGroup>

<Note>
  Alle Claude-Modelle sind mit integrierten Sicherheitsverhaltensweisen trainiert. Dies kann dazu führen, dass Claude Inhalte moderiert, die als besonders gefährlich eingestuft werden (im Einklang mit der 

  [Acceptable Use Policy](https://www.anthropic.com/legal/aup)

  ), unabhängig vom verwendeten Prompt. Beispielsweise könnte eine Website für Erwachsene, die Nutzern das Posten expliziter sexueller Inhalte erlauben möchte, feststellen, dass Claude explizite Inhalte weiterhin als moderationsbedürftig kennzeichnet, selbst wenn im Prompt angegeben wird, explizite sexuelle Inhalte nicht zu moderieren. Ziehe in Betracht, die AUP zu prüfen, bevor du eine Moderationslösung entwickelst.
</Note>

### Generiere Beispiele für zu moderierende Inhalte

Bevor du eine Lösung zur Inhaltsmoderation entwickelst, erstelle zunächst Beispiele für Inhalte, die gekennzeichnet werden sollten, und für Inhalte, die nicht gekennzeichnet werden sollten. Achte darauf, Grenzfälle und anspruchsvolle Szenarien einzubeziehen, die für ein Inhaltsmoderationssystem schwer effektiv zu handhaben sein könnten. Überprüfe anschließend deine Beispiele, um eine klar definierte Liste von Moderationskategorien zu erstellen. Die von einer Social-Media-Plattform generierten Beispiele könnten etwa Folgendes umfassen:

<CodeGroup exclude="shell">
  ```python Python
  client = anthropic.Anthropic()

  allowed_user_comments = [
      "This movie was great, I really enjoyed it. The main actor really killed it!",
      "I hate Mondays.",
      "It is a great time to invest in gold!",
  ]

  disallowed_user_comments = [
      "Delete this post now or you better hide. I am coming after you and your family.",
      "Stay away from the 5G cellphones!! They are using 5G to control you.",
      "Congratulations! You have won a $1,000 gift card. Click here to claim your prize!",
  ]

  # Beispiel-Nutzerkommentare zum Testen der Content-Moderation
  user_comments = allowed_user_comments + disallowed_user_comments

  # Kategorien, die für die Content-Moderation als unsicher gelten
  unsafe_categories = [
      "Child Exploitation",
      "Conspiracy Theories",
      "Hate",
      "Indiscriminate Weapons",
      "Intellectual Property",
      "Non-Violent Crimes",
      "Privacy",
      "Self-Harm",
      "Sex Crimes",
      "Sexual Content",
      "Specialized Advice",
      "Violent Crimes",
  ]
  ```

  ```typescript TypeScript
  const client = new Anthropic();

  const allowedUserComments = [
    "This movie was great, I really enjoyed it. The main actor really killed it!",
    "I hate Mondays.",
    "It is a great time to invest in gold!"
  ];

  const disallowedUserComments = [
    "Delete this post now or you better hide. I am coming after you and your family.",
    "Stay away from the 5G cellphones!! They are using 5G to control you.",
    "Congratulations! You have won a $1,000 gift card. Click here to claim your prize!"
  ];

  // Beispiel-Nutzerkommentare zum Testen der Content-Moderation
  const userComments = [...allowedUserComments, ...disallowedUserComments];

  // Kategorien, die für die Content-Moderation als unsicher gelten
  const unsafeCategories = [
    "Child Exploitation",
    "Conspiracy Theories",
    "Hate",
    "Indiscriminate Weapons",
    "Intellectual Property",
    "Non-Violent Crimes",
    "Privacy",
    "Self-Harm",
    "Sex Crimes",
    "Sexual Content",
    "Specialized Advice",
    "Violent Crimes"
  ];
  ```

  ```csharp C#
  var client = new AnthropicClient();

  string[] allowedUserComments =
  [
      "This movie was great, I really enjoyed it. The main actor really killed it!",
      "I hate Mondays.",
      "It is a great time to invest in gold!",
  ];

  string[] disallowedUserComments =
  [
      "Delete this post now or you better hide. I am coming after you and your family.",
      "Stay away from the 5G cellphones!! They are using 5G to control you.",
      "Congratulations! You have won a $1,000 gift card. Click here to claim your prize!",
  ];

  // Beispiel-Nutzerkommentare zum Testen der Content-Moderation
  string[] userComments = [.. allowedUserComments, .. disallowedUserComments];

  // Kategorien, die für die Content-Moderation als unsicher gelten
  string[] unsafeCategories =
  [
      "Child Exploitation",
      "Conspiracy Theories",
      "Hate",
      "Indiscriminate Weapons",
      "Intellectual Property",
      "Non-Violent Crimes",
      "Privacy",
      "Self-Harm",
      "Sex Crimes",
      "Sexual Content",
      "Specialized Advice",
      "Violent Crimes",
  ];
  ```

  ```go Go
  var client = anthropic.NewClient()

  var allowedUserComments = []string{
  	"This movie was great, I really enjoyed it. The main actor really killed it!",
  	"I hate Mondays.",
  	"It is a great time to invest in gold!",
  }

  var disallowedUserComments = []string{
  	"Delete this post now or you better hide. I am coming after you and your family.",
  	"Stay away from the 5G cellphones!! They are using 5G to control you.",
  	"Congratulations! You have won a $1,000 gift card. Click here to claim your prize!",
  }

  // Beispiel-Nutzerkommentare zum Testen der Content-Moderation
  var userComments = slices.Concat(allowedUserComments, disallowedUserComments)

  // Kategorien, die für die Content-Moderation als unsicher gelten
  var unsafeCategories = []string{
  	"Child Exploitation",
  	"Conspiracy Theories",
  	"Hate",
  	"Indiscriminate Weapons",
  	"Intellectual Property",
  	"Non-Violent Crimes",
  	"Privacy",
  	"Self-Harm",
  	"Sex Crimes",
  	"Sexual Content",
  	"Specialized Advice",
  	"Violent Crimes",
  }
  ```

  ```java Java
  final AnthropicClient client = AnthropicOkHttpClient.fromEnv();

  final List<String> allowedUserComments = List.of(
          "This movie was great, I really enjoyed it. The main actor really killed it!",
          "I hate Mondays.",
          "It is a great time to invest in gold!");

  final List<String> disallowedUserComments = List.of(
          "Delete this post now or you better hide. I am coming after you and your family.",
          "Stay away from the 5G cellphones!! They are using 5G to control you.",
          "Congratulations! You have won a $1,000 gift card. Click here to claim your prize!");

  // Beispiel-Nutzerkommentare zum Testen der Content-Moderation
  final List<String> userComments =
          Stream.concat(allowedUserComments.stream(), disallowedUserComments.stream()).toList();

  // Kategorien, die für die Content-Moderation als unsicher gelten
  final List<String> unsafeCategories = List.of(
          "Child Exploitation",
          "Conspiracy Theories",
          "Hate",
          "Indiscriminate Weapons",
          "Intellectual Property",
          "Non-Violent Crimes",
          "Privacy",
          "Self-Harm",
          "Sex Crimes",
          "Sexual Content",
          "Specialized Advice",
          "Violent Crimes");
  ```

  ```php PHP
  $client = new Client();

  $allowedUserComments = [
      'This movie was great, I really enjoyed it. The main actor really killed it!',
      'I hate Mondays.',
      'It is a great time to invest in gold!',
  ];

  $disallowedUserComments = [
      'Delete this post now or you better hide. I am coming after you and your family.',
      'Stay away from the 5G cellphones!! They are using 5G to control you.',
      'Congratulations! You have won a $1,000 gift card. Click here to claim your prize!',
  ];

  // Beispiel-Nutzerkommentare zum Testen der Content-Moderation
  $userComments = [...$allowedUserComments, ...$disallowedUserComments];

  // Kategorien, die für die Content-Moderation als unsicher gelten
  $unsafeCategories = [
      'Child Exploitation',
      'Conspiracy Theories',
      'Hate',
      'Indiscriminate Weapons',
      'Intellectual Property',
      'Non-Violent Crimes',
      'Privacy',
      'Self-Harm',
      'Sex Crimes',
      'Sexual Content',
      'Specialized Advice',
      'Violent Crimes',
  ];
  ```

  ```ruby Ruby
  CLIENT = Anthropic::Client.new

  ALLOWED_USER_COMMENTS = [
    "This movie was great, I really enjoyed it. The main actor really killed it!",
    "I hate Mondays.",
    "It is a great time to invest in gold!"
  ]

  DISALLOWED_USER_COMMENTS = [
    "Delete this post now or you better hide. I am coming after you and your family.",
    "Stay away from the 5G cellphones!! They are using 5G to control you.",
    "Congratulations! You have won a $1,000 gift card. Click here to claim your prize!"
  ]

  # Beispiel-Nutzerkommentare zum Testen der Content-Moderation
  USER_COMMENTS = ALLOWED_USER_COMMENTS + DISALLOWED_USER_COMMENTS

  # Kategorien, die für die Content-Moderation als unsicher gelten
  UNSAFE_CATEGORIES = [
    "Child Exploitation",
    "Conspiracy Theories",
    "Hate",
    "Indiscriminate Weapons",
    "Intellectual Property",
    "Non-Violent Crimes",
    "Privacy",
    "Self-Harm",
    "Sex Crimes",
    "Sexual Content",
    "Specialized Advice",
    "Violent Crimes"
  ]
  ```
</CodeGroup>

Die effektive Moderation dieser Beispiele erfordert ein nuanciertes Sprachverständnis. Beim Kommentar `This movie was great, I really enjoyed it. The main actor really killed it!` muss das Inhaltsmoderationssystem erkennen, dass „killed it“ eine Metapher ist und kein Hinweis auf tatsächliche Gewalt. Umgekehrt sollte der Kommentar `Delete this post now or you better hide. I am coming after you and your family.` vom Inhaltsmoderationssystem gekennzeichnet werden, obwohl Gewalt nicht explizit erwähnt wird.

Die unsicheren Kategorien können an deine spezifischen Bedürfnisse angepasst werden. Wenn du beispielsweise verhindern möchtest, dass Minderjährige Inhalte auf deiner Website erstellen, könntest du „Underage Posting“ zu den Kategorien hinzufügen.

***

## So moderierst du Inhalte mit Claude

### Wähle das richtige Claude-Modell

Bei der Auswahl eines Modells ist es wichtig, die Größe deiner Daten zu berücksichtigen. Wenn die Kosten eine Rolle spielen, ist ein kleineres Modell wie Claude Haiku 5.5 aufgrund seiner Kosteneffizienz eine ausgezeichnete Wahl. Im Folgenden findest du eine Schätzung der Kosten für die Moderation von Text für eine Social-Media-Plattform, die eine Milliarde Posts pro Monat erhält:

* **Inhaltsumfang**

  * Posts pro Monat: 1 Mrd.
  * Zeichen pro Post: 100
  * Zeichen insgesamt: 100 Mrd.

* **Geschätzte Token**

  * Input-Token: 28,6 Mrd. (bei angenommen 1 Token pro 3,5 Zeichen)
  * Anteil gekennzeichneter Nachrichten: 3 %
  * Output-Token pro gekennzeichneter Nachricht: 50
  * Output-Token insgesamt: 1,5 Mrd.

* **Geschätzte Kosten für Claude Haiku 5.5**

  * Kosten für Input-Token: 28.600 MTok \* 0,10 $ / MTok = 2.860 USD
  * Kosten für Output-Token: 1.500 MTok \* 0,50 $ / MTok = 750 USD
  * Monatliche Kosten: 2.860 $ + 750 $ = 3.610 USD

* **Geschätzte Kosten für Claude Opus 5**

  * Kosten für Input-Token: 28.600 MTok \* 5,00 $ / MTok = 143.000 USD
  * Kosten für Output-Token: 1.500 MTok \* 25,00 $ / MTok = 37.500 USD
  * Monatliche Kosten: 143.000 $ + 37.500 $ = 180.500 USD

* **Geschätzte Kosten für Claude Opus 4.8**

  * Kosten für Input-Token: 28.600 MTok \* 5,00 $ / MTok = 143.000 USD
  * Kosten für Output-Token: 1.500 MTok \* 25,00 $ / MTok = 37.500 USD
  * Monatliche Kosten: 143.000 $ + 37.500 $ = 180.500 USD

<Tip>
  Die tatsächlichen Kosten können von diesen Schätzungen abweichen. Diese Schätzungen basieren auf dem Prompt, der im Abschnitt zur 

  [Batch-Verarbeitung](https://platform.claude.com/docs/de/about-claude/use-case-guides/content-moderation#consider-batch-processing)

   vorgestellt wird. Die Output-Token lassen sich noch weiter reduzieren, indem das Feld 

  `explanation`

   aus der Antwort entfernt wird.
</Tip>

### Erstelle einen starken Prompt

Um Claude für die Inhaltsmoderation zu verwenden, muss Claude die Moderationsanforderungen deiner Anwendung verstehen. Beginne damit, einen Prompt zu schreiben, mit dem du deine Moderationsbedürfnisse definieren kannst:

<CodeGroup exclude="shell">
  ```python Python
  def moderate_message(message, unsafe_categories):
      # Wandle die unsicheren Kategorien in einen String um, mit jeder Kategorie in einer neuen Zeile
      unsafe_category_str = "\n".join(unsafe_categories)

      # Erstelle den Prompt für Claude, einschließlich der Nachricht und der unsicheren Kategorien
      assessment_prompt = f"""
      Determine whether the following message warrants moderation,
      based on the unsafe categories outlined below.

      Message:
      <message>{message}</message>

      Unsafe Categories:
      <categories>
      {unsafe_category_str}
      </categories>

      Respond with ONLY a JSON object, using the format below:
      {{
      "violation": <Boolean field denoting whether the message should be moderated>,
      "categories": [Comma-separated list of violated categories],
      "explanation": [Optional. Only include if there is a violation.]
      }}
  Do not include markdown formatting or code fences in your response."""

      # Sende die Anfrage zur Content-Moderation an Claude
      response = client.messages.create(
          model="claude-haiku-4-5-20251001",  # Using the Haiku model for lower costs
          max_tokens=200,
          messages=[{"role": "user", "content": assessment_prompt}],
      )

      # Parse die JSON-Antwort von Claude
      text_block = next(block for block in response.content if block.type == "text")
      assessment = json.loads(text_block.text)

      # Extrahiere den Verstoß-Status aus der Bewertung
      contains_violation = assessment["violation"]

      # Bei einem Verstoß hole die Kategorien und die Erklärung; andernfalls verwende leere Standardwerte
      violated_categories = assessment.get("categories", []) if contains_violation else []
      explanation = assessment.get("explanation") if contains_violation else None

      return contains_violation, violated_categories, explanation


  # Verarbeite jeden Kommentar und gib die Ergebnisse aus
  for comment in user_comments:
      print(f"\nComment: {comment}")
      violation, violated_categories, explanation = moderate_message(
          comment, unsafe_categories
      )

      if violation:
          print(f"Violated Categories: {', '.join(violated_categories)}")
          print(f"Explanation: {explanation}")
      else:
          print("No issues detected.")
  ```

  ```typescript TypeScript
  // Struktur der JSON-Bewertung, die Claude zurückgibt
  interface ModerationAssessment {
    violation: boolean;
    categories?: string[];
    explanation?: string;
  }

  async function moderateMessage(
    message: string,
    unsafeCategories: string[]
  ): Promise<{ violation: boolean; violatedCategories: string[]; explanation?: string }> {
    // Wandle die unsicheren Kategorien in einen String um, mit jeder Kategorie in einer neuen Zeile
    const unsafeCategoryStr = unsafeCategories.join("\n");

    // Erstelle den Prompt für Claude, einschließlich der Nachricht und der unsicheren Kategorien
    const assessmentPrompt = `
      Determine whether the following message warrants moderation,
      based on the unsafe categories outlined below.

      Message:
      <message>${message}</message>

      Unsafe Categories:
      <categories>
      ${unsafeCategoryStr}
      </categories>

      Respond with ONLY a JSON object, using the format below:
      {
      "violation": <Boolean field denoting whether the message should be moderated>,
      "categories": [Comma-separated list of violated categories],
      "explanation": [Optional. Only include if there is a violation.]
      }
  Do not include markdown formatting or code fences in your response.`;

    // Sende die Anfrage zur Content-Moderation an Claude
    const response = await client.messages.create({
      model: "claude-haiku-4-5-20251001", // Using the Haiku model for lower costs
      max_tokens: 200,
      messages: [{ role: "user", content: assessmentPrompt }]
    });

    // Parse die JSON-Antwort von Claude
    const textBlock = response.content.find((block) => block.type === "text");
    if (!textBlock) {
      throw new Error("Expected a text block in the response");
    }
    const assessment: ModerationAssessment = JSON.parse(textBlock.text);

    // Extrahiere den Verstoß-Status aus der Bewertung
    const containsViolation = assessment.violation;

    // Bei einem Verstoß hole die Kategorien und die Erklärung; andernfalls verwende leere Standardwerte
    const violatedCategories = containsViolation ? (assessment.categories ?? []) : [];
    const explanation = containsViolation ? assessment.explanation : undefined;

    return { violation: containsViolation, violatedCategories, explanation };
  }

  // Verarbeite jeden Kommentar und gib die Ergebnisse aus
  for (const comment of userComments) {
    console.log(`\nComment: ${comment}`);
    const { violation, violatedCategories, explanation } = await moderateMessage(
      comment,
      unsafeCategories
    );

    if (violation) {
      console.log(`Violated Categories: ${violatedCategories.join(", ")}`);
      console.log(`Explanation: ${explanation}`);
    } else {
      console.log("No issues detected.");
    }
  }
  ```

  ```csharp C#
  async Task<(bool ContainsViolation, List<string> ViolatedCategories, string? Explanation)> ModerateMessage(
      string message,
      IReadOnlyList<string> categories
  )
  {
      // Wandle die unsicheren Kategorien in einen String um, mit jeder Kategorie in einer neuen Zeile
      var unsafeCategoryText = string.Join("\n", categories);

      // Erstelle den Prompt für Claude, einschließlich der Nachricht und der unsicheren Kategorien
      var assessmentPrompt = $$"""

      Determine whether the following message warrants moderation,
      based on the unsafe categories outlined below.

      Message:
      <message>{{message}}</message>

      Unsafe Categories:
      <categories>
      {{unsafeCategoryText}}
      </categories>

      Respond with ONLY a JSON object, using the format below:
      {
      "violation": <Boolean field denoting whether the message should be moderated>,
      "categories": [Comma-separated list of violated categories],
      "explanation": [Optional. Only include if there is a violation.]
      }
  Do not include markdown formatting or code fences in your response.
  """;

      // Sende die Anfrage zur Content-Moderation an Claude
      var response = await client.Messages.Create(
          new()
          {
              Model = Model.ClaudeHaiku4_5_20251001, // Using the Haiku model for lower costs
              MaxTokens = 200,
              Messages = [new() { Role = Role.User, Content = assessmentPrompt }],
          }
      );

      // Grenze den ersten Content-Block auf einen Textblock ein und parse dann Claudes JSON-Antwort
      if (!response.Content[0].TryPickText(out var textBlock))
      {
          throw new InvalidOperationException("Expected a text response from Claude.");
      }
      var assessment = JsonNode.Parse(textBlock.Text)!;

      // Extrahiere den Verstoß-Status aus der Bewertung
      var containsViolation = assessment["violation"]!.GetValue<bool>();

      // Bei einem Verstoß hole die Kategorien und die Erklärung; andernfalls verwende leere Standardwerte
      List<string> violatedCategories = containsViolation
          ? assessment["categories"]?.AsArray().Select(category => category!.GetValue<string>()).ToList() ?? []
          : [];
      var explanation = containsViolation ? assessment["explanation"]?.GetValue<string>() : null;

      return (containsViolation, violatedCategories, explanation);
  }

  // Verarbeite jeden Kommentar und gib die Ergebnisse aus
  foreach (var comment in userComments)
  {
      Console.WriteLine($"\nComment: {comment}");
      var (violation, violatedCategories, explanation) = await ModerateMessage(comment, unsafeCategories);

      if (violation)
      {
          Console.WriteLine($"Violated Categories: {string.Join(", ", violatedCategories)}");
          Console.WriteLine($"Explanation: {explanation}");
      }
      else
      {
          Console.WriteLine("No issues detected.");
      }
  }
  ```

  ```go Go
  func moderateMessage(message string, unsafeCategories []string) (bool, []string, string) {
  	// Wandle die unsicheren Kategorien in einen String um, mit jeder Kategorie in einer neuen Zeile
  	unsafeCategoryStr := strings.Join(unsafeCategories, "\n")

  	// Erstelle den Prompt für Claude, einschließlich der Nachricht und der unsicheren Kategorien
  	assessmentPrompt := fmt.Sprintf(`
      Determine whether the following message warrants moderation,
      based on the unsafe categories outlined below.

      Message:
      <message>%s</message>

      Unsafe Categories:
      <categories>
      %s
      </categories>

      Respond with ONLY a JSON object, using the format below:
      {
      "violation": <Boolean field denoting whether the message should be moderated>,
      "categories": [Comma-separated list of violated categories],
      "explanation": [Optional. Only include if there is a violation.]
      }
  Do not include markdown formatting or code fences in your response.`, message, unsafeCategoryStr)

  	// Sende die Anfrage zur Content-Moderation an Claude
  	response, err := client.Messages.New(context.Background(), anthropic.MessageNewParams{
  		Model:     anthropic.ModelClaudeHaiku4_5_20251001, // Using the Haiku model for lower costs
  		MaxTokens: 200,
  		Messages: []anthropic.MessageParam{
  			anthropic.NewUserMessage(anthropic.NewTextBlock(assessmentPrompt)),
  		},
  	})
  	if err != nil {
  		log.Fatal(err)
  	}

  	// Grenze den ersten Content-Block auf einen Textblock ein, bevor du dessen Text liest
  	textBlock, ok := response.Content[0].AsAny().(anthropic.TextBlock)
  	if !ok {
  		log.Fatalf("expected a text block, got %q", response.Content[0].Type)
  	}

  	// Parse die JSON-Antwort von Claude
  	var assessment struct {
  		Violation   bool     `json:"violation"`
  		Categories  []string `json:"categories"`
  		Explanation string   `json:"explanation"`
  	}
  	if err := json.Unmarshal([]byte(textBlock.Text), &assessment); err != nil {
  		log.Fatal(err)
  	}

  	// Bei einem Verstoß gib die Kategorien und die Erklärung zurück; andernfalls verwende leere Standardwerte
  	if !assessment.Violation {
  		return false, nil, ""
  	}
  	return true, assessment.Categories, assessment.Explanation
  }

  // moderateAllComments verarbeitet jeden Kommentar und gibt die Ergebnisse aus.
  func moderateAllComments() {
  	for _, comment := range userComments {
  		fmt.Printf("\nComment: %s\n", comment)
  		violation, violatedCategories, explanation := moderateMessage(comment, unsafeCategories)

  		if violation {
  			fmt.Printf("Violated Categories: %s\n", strings.Join(violatedCategories, ", "))
  			fmt.Printf("Explanation: %s\n", explanation)
  		} else {
  			fmt.Println("No issues detected.")
  		}
  	}
  }
  ```

  ```java Java
  record ModerationResult(boolean violation, List<String> violatedCategories, String explanation) {}

  ModerationResult moderateMessage(String message, List<String> unsafeCategories)
          throws JsonProcessingException {
      // Wandle die unsicheren Kategorien in einen String um, mit jeder Kategorie in einer neuen Zeile
      String unsafeCategoryStr = String.join("\n", unsafeCategories);

      // Erstelle den Prompt für Claude, einschließlich der Nachricht und der unsicheren Kategorien
      String assessmentPrompt = """

              Determine whether the following message warrants moderation,
              based on the unsafe categories outlined below.

              Message:
              <message>%s</message>

              Unsafe Categories:
              <categories>
              %s
              </categories>

              Respond with ONLY a JSON object, using the format below:
              {
              "violation": <Boolean field denoting whether the message should be moderated>,
              "categories": [Comma-separated list of violated categories],
              "explanation": [Optional. Only include if there is a violation.]
              }
          Do not include markdown formatting or code fences in your response."""
              .formatted(message, unsafeCategoryStr);

      // Sende die Anfrage zur Content-Moderation an Claude
      Message response = client.messages().create(MessageCreateParams.builder()
              .model(Model.CLAUDE_HAIKU_4_5_20251001) // Using the Haiku model for lower costs
              .maxTokens(200)
              .addUserMessage(assessmentPrompt)
              .build());

      // Parse die JSON-Antwort von Claude
      String assessmentJson = response.content().stream()
              .flatMap(contentBlock -> contentBlock.text().stream())
              .findFirst()
              .orElseThrow()
              .text();
      ObjectMapper mapper = new ObjectMapper();
      JsonNode assessment = mapper.readTree(assessmentJson);

      // Extrahiere den Verstoß-Status aus der Bewertung
      boolean containsViolation = assessment.required("violation").asBoolean();

      // Bei einem Verstoß hole die Kategorien und die Erklärung; andernfalls verwende leere Standardwerte
      List<String> violatedCategories = containsViolation && assessment.has("categories")
              ? mapper.convertValue(assessment.get("categories"), new TypeReference<List<String>>() {})
              : List.of();
      String explanation = containsViolation && assessment.hasNonNull("explanation")
              ? assessment.get("explanation").asText()
              : null;

      return new ModerationResult(containsViolation, violatedCategories, explanation);
  }

  // Verarbeite jeden Kommentar und gib die Ergebnisse aus
  void printModerationResults() throws JsonProcessingException {
      for (String comment : userComments) {
          IO.println("\nComment: " + comment);
          ModerationResult result = moderateMessage(comment, unsafeCategories);

          if (result.violation()) {
              IO.println("Violated Categories: " + String.join(", ", result.violatedCategories()));
              IO.println("Explanation: " + result.explanation());
          } else {
              IO.println("No issues detected.");
          }
      }
  }
  ```

  ```php PHP
  $moderateMessage = function (string $message, array $unsafeCategories) use ($client): array {
      // Wandle die unsicheren Kategorien in einen String um, mit jeder Kategorie in einer neuen Zeile
      $unsafeCategoryStr = implode("\n", $unsafeCategories);

      // Erstelle den Prompt für Claude, einschließlich der Nachricht und der unsicheren Kategorien
      $assessmentPrompt = <<<PROMPT

          Determine whether the following message warrants moderation,
          based on the unsafe categories outlined below.

          Message:
          <message>{$message}</message>

          Unsafe Categories:
          <categories>
          {$unsafeCategoryStr}
          </categories>

          Respond with ONLY a JSON object, using the format below:
          {
          "violation": <Boolean field denoting whether the message should be moderated>,
          "categories": [Comma-separated list of violated categories],
          "explanation": [Optional. Only include if there is a violation.]
          }
      Do not include markdown formatting or code fences in your response.
      PROMPT;

      // Sende die Anfrage zur Content-Moderation an Claude
      $response = $client->messages->create(
          model: 'claude-haiku-4-5-20251001', // Using the Haiku model for lower costs
          maxTokens: 200,
          messages: [['role' => 'user', 'content' => $assessmentPrompt]],
      );

      // Parse die JSON-Antwort von Claude. Das SDK dekodiert jeden Content-Block
      // in seine konkrete Klasse, finde also den TextBlock, bevor du den Text liest.
      $textBlock = array_find($response->content, fn ($block) => $block instanceof \Anthropic\Messages\TextBlock)
          ?? throw new \RuntimeException('Expected a text block in the response.');
      $assessment = json_decode($textBlock->text, associative: true, flags: JSON_THROW_ON_ERROR);

      // Extrahiere den Verstoß-Status aus der Bewertung
      $containsViolation = $assessment['violation'];

      // Bei einem Verstoß hole die Kategorien und die Erklärung; andernfalls verwende leere Standardwerte
      $violatedCategories = $containsViolation ? ($assessment['categories'] ?? []) : [];
      $explanation = $containsViolation ? ($assessment['explanation'] ?? null) : null;

      return [$containsViolation, $violatedCategories, $explanation];
  };

  // Verarbeite jeden Kommentar und gib die Ergebnisse aus
  foreach ($userComments as $comment) {
      echo "\nComment: {$comment}\n";
      [$violation, $violatedCategories, $explanation] = $moderateMessage($comment, $unsafeCategories);

      if ($violation) {
          echo 'Violated Categories: ' . implode(', ', $violatedCategories) . "\n";
          echo "Explanation: {$explanation}\n";
      } else {
          echo "No issues detected.\n";
      }
  }
  ```

  ```ruby Ruby
  def moderate_message(message, unsafe_categories)
    # Wandle die unsicheren Kategorien in einen String um, mit jeder Kategorie in einer neuen Zeile
    unsafe_category_str = unsafe_categories.join("\n")

    # Erstelle den Prompt für Claude, einschließlich der Nachricht und der unsicheren Kategorien
    assessment_prompt = <<~PROMPT.chomp

          Determine whether the following message warrants moderation,
          based on the unsafe categories outlined below.

          Message:
          <message>#{message}</message>

          Unsafe Categories:
          <categories>
          #{unsafe_category_str}
          </categories>

          Respond with ONLY a JSON object, using the format below:
          {
          "violation": <Boolean field denoting whether the message should be moderated>,
          "categories": [Comma-separated list of violated categories],
          "explanation": [Optional. Only include if there is a violation.]
          }
      Do not include markdown formatting or code fences in your response.
    PROMPT

    # Sende die Anfrage zur Content-Moderation an Claude
    response = CLIENT.messages.create(
      model: "claude-haiku-4-5-20251001", # Using the Haiku model for lower costs
      max_tokens: 200,
      messages: [{role: :user, content: assessment_prompt}]
    )

    # Parse die JSON-Antwort von Claude
    text_block = response.content.find { it.type == :text }
    assessment = JSON.parse(text_block.text)

    # Extrahiere den Verstoß-Status aus der Bewertung
    contains_violation = assessment["violation"]

    # Wenn ein Verstoß vorliegt, hole die Kategorien und die Erklärung; andernfalls verwende leere Standardwerte
    violated_categories = contains_violation ? assessment.fetch("categories", []) : []
    explanation = contains_violation ? assessment["explanation"] : nil

    [contains_violation, violated_categories, explanation]
  end


  # Verarbeite jeden Kommentar und gib die Ergebnisse aus
  USER_COMMENTS.each do |comment|
    puts "\nComment: #{comment}"
    violation, violated_categories, explanation = moderate_message(comment, UNSAFE_CATEGORIES)

    if violation
      puts "Violated Categories: #{violated_categories.join(", ")}"
      puts "Explanation: #{explanation}"
    else
      puts "No issues detected."
    end
  end
  ```
</CodeGroup>

In diesem Beispiel enthält die Funktion `moderate_message` einen Bewertungs-Prompt, der die unsicheren Inhaltskategorien und die zu bewertende Nachricht umfasst. Der Prompt fordert Claude auf, anhand der zuvor von dir definierten unsicheren Kategorien zu beurteilen, ob die Nachricht moderiert werden sollte.

Die Bewertung des Modells wird anschließend geparst, um festzustellen, ob ein Verstoß vorliegt. Liegt ein Verstoß vor, gibt Claude zusätzlich eine Liste der verletzten Kategorien sowie eine Erklärung zurück, warum die Nachricht unsicher ist.

### Evaluiere deinen Prompt

Inhaltsmoderation ist ein Klassifizierungsproblem. Daher kannst du dieselben Techniken verwenden, die im [Klassifizierungs-Cookbook](https://platform.claude.com/cookbook/capabilities-classification-guide) beschrieben sind, um die Genauigkeit deines Inhaltsmoderationssystems zu bestimmen.

Eine zusätzliche Überlegung ist, dass du Inhaltsmoderation nicht als binäres Klassifizierungsproblem behandeln musst, sondern stattdessen mehrere Kategorien erstellen kannst, die verschiedene Risikostufen repräsentieren. Durch das Erstellen mehrerer Risikostufen kannst du die Strenge deiner Moderation anpassen. Beispielsweise möchtest du vielleicht Nutzeranfragen, die als hohes Risiko eingestuft werden, automatisch blockieren, während Nutzer mit vielen Anfragen mittleren Risikos zur menschlichen Überprüfung gekennzeichnet werden.

<CodeGroup exclude="shell">
  ```python Python
  def assess_risk_level(message, unsafe_categories):
      # Wandle die unsicheren Kategorien in einen String um, mit jeder Kategorie in einer neuen Zeile
      unsafe_category_str = "\n".join(unsafe_categories)

      # Erstelle den Prompt für Claude, einschließlich der Nachricht, der unsicheren Kategorien und der Risikostufen-Definitionen
      assessment_prompt = f"""
      Assess the risk level of the following message,
      based on the unsafe categories listed below.

  Message:
  <message>{message}</message>

  Unsafe Categories:
  <categories>
  {unsafe_category_str}
  </categories>

  Assign a risk level based on your confidence that the user's message should be moderated
  based on the defined unsafe categories:

  0 - No risk
  1 - Low risk
  2 - Medium risk
  3 - High risk

  Respond with ONLY a JSON object, using the format below:
  {{
    "risk_level": <Numerical field denoting the risk level>,
    "categories": [Comma-separated list of violated categories],
    "explanation": <Optional. Only include if risk level is greater than 0>
  }}
  Do not include markdown formatting or code fences in your response."""

      # Sende die Anfrage zur Risikobewertung an Claude
      response = client.messages.create(
          model="claude-haiku-4-5-20251001",  # Using the Haiku model for lower costs
          max_tokens=200,
          messages=[{"role": "user", "content": assessment_prompt}],
      )

      # Parse die JSON-Antwort von Claude
      text_block = next(block for block in response.content if block.type == "text")
      assessment = json.loads(text_block.text)

      # Extrahiere die Risikostufe, die verletzten Kategorien und die Erklärung aus der Bewertung
      risk_level = assessment["risk_level"]
      violated_categories = assessment["categories"]
      explanation = assessment.get("explanation")

      return risk_level, violated_categories, explanation


  # Verarbeite jeden Kommentar und gib die Ergebnisse aus
  for comment in user_comments:
      print(f"\nComment: {comment}")
      risk_level, violated_categories, explanation = assess_risk_level(
          comment, unsafe_categories
      )

      print(f"Risk Level: {risk_level}")
      if violated_categories:
          print(f"Violated Categories: {', '.join(violated_categories)}")
      if explanation:
          print(f"Explanation: {explanation}")
  ```

  ```typescript TypeScript
  // Struktur der JSON-Risikobewertung, die Claude zurückgibt
  interface RiskAssessment {
    risk_level: number;
    categories: string[];
    explanation?: string;
  }

  async function assessRiskLevel(
    message: string,
    unsafeCategories: string[]
  ): Promise<{ riskLevel: number; violatedCategories: string[]; explanation?: string }> {
    // Wandle die unsicheren Kategorien in einen String um, mit jeder Kategorie in einer neuen Zeile
    const unsafeCategoryStr = unsafeCategories.join("\n");

    // Erstelle den Prompt für Claude, einschließlich der Nachricht, der unsicheren Kategorien und der Risikostufen-Definitionen
    const assessmentPrompt = `
      Assess the risk level of the following message,
      based on the unsafe categories listed below.

  Message:
  <message>${message}</message>

  Unsafe Categories:
  <categories>
  ${unsafeCategoryStr}
  </categories>

  Assign a risk level based on your confidence that the user's message should be moderated
  based on the defined unsafe categories:

  0 - No risk
  1 - Low risk
  2 - Medium risk
  3 - High risk

  Respond with ONLY a JSON object, using the format below:
  {
    "risk_level": <Numerical field denoting the risk level>,
    "categories": [Comma-separated list of violated categories],
    "explanation": <Optional. Only include if risk level is greater than 0>
  }
  Do not include markdown formatting or code fences in your response.`;

    // Sende die Anfrage zur Risikobewertung an Claude
    const response = await client.messages.create({
      model: "claude-haiku-4-5-20251001", // Using the Haiku model for lower costs
      max_tokens: 200,
      messages: [{ role: "user", content: assessmentPrompt }]
    });

    // Parse die JSON-Antwort von Claude
    const textBlock = response.content.find((block) => block.type === "text");
    if (!textBlock) {
      throw new Error("Expected a text block in the response");
    }
    const assessment: RiskAssessment = JSON.parse(textBlock.text);

    // Extrahiere die Risikostufe, die verletzten Kategorien und die Erklärung aus der Bewertung
    const { risk_level: riskLevel, categories: violatedCategories, explanation } = assessment;

    return { riskLevel, violatedCategories, explanation };
  }

  // Verarbeite jeden Kommentar und gib die Ergebnisse aus
  for (const comment of userComments) {
    console.log(`\nComment: ${comment}`);
    const { riskLevel, violatedCategories, explanation } = await assessRiskLevel(
      comment,
      unsafeCategories
    );

    console.log(`Risk Level: ${riskLevel}`);
    if (violatedCategories.length > 0) {
      console.log(`Violated Categories: ${violatedCategories.join(", ")}`);
    }
    if (explanation) {
      console.log(`Explanation: ${explanation}`);
    }
  }
  ```

  ```csharp C#
  async Task<(int RiskLevel, List<string> ViolatedCategories, string? Explanation)> AssessRiskLevel(
      string message,
      IReadOnlyList<string> categories
  )
  {
      // Wandle die unsicheren Kategorien in einen String um, mit jeder Kategorie in einer neuen Zeile
      var unsafeCategoryText = string.Join("\n", categories);

      // Erstelle den Prompt für Claude, einschließlich der Nachricht, der unsicheren Kategorien und der Risikostufen-Definitionen
      var assessmentPrompt = $$"""

      Assess the risk level of the following message,
      based on the unsafe categories listed below.

  Message:
  <message>{{message}}</message>

  Unsafe Categories:
  <categories>
  {{unsafeCategoryText}}
  </categories>

  Assign a risk level based on your confidence that the user's message should be moderated
  based on the defined unsafe categories:

  0 - No risk
  1 - Low risk
  2 - Medium risk
  3 - High risk

  Respond with ONLY a JSON object, using the format below:
  {
    "risk_level": <Numerical field denoting the risk level>,
    "categories": [Comma-separated list of violated categories],
    "explanation": <Optional. Only include if risk level is greater than 0>
  }
  Do not include markdown formatting or code fences in your response.
  """;

      // Sende die Anfrage zur Risikobewertung an Claude
      var response = await client.Messages.Create(
          new()
          {
              Model = Model.ClaudeHaiku4_5_20251001, // Using the Haiku model for lower costs
              MaxTokens = 200,
              Messages = [new() { Role = Role.User, Content = assessmentPrompt }],
          }
      );

      // Grenze den ersten Content-Block auf einen Textblock ein und parse dann Claudes JSON-Antwort
      if (!response.Content[0].TryPickText(out var textBlock))
      {
          throw new InvalidOperationException("Expected a text response from Claude.");
      }
      var assessment = JsonNode.Parse(textBlock.Text)!;

      // Extrahiere die Risikostufe, die verletzten Kategorien und die Erklärung aus der Bewertung
      var riskLevel = assessment["risk_level"]!.GetValue<int>();
      var violatedCategories = assessment["categories"]!
          .AsArray()
          .Select(category => category!.GetValue<string>())
          .ToList();
      var explanation = assessment["explanation"]?.GetValue<string>();

      return (riskLevel, violatedCategories, explanation);
  }

  // Verarbeite jeden Kommentar und gib die Ergebnisse aus
  foreach (var comment in userComments)
  {
      Console.WriteLine($"\nComment: {comment}");
      var (riskLevel, violatedCategories, explanation) = await AssessRiskLevel(comment, unsafeCategories);

      Console.WriteLine($"Risk Level: {riskLevel}");
      if (violatedCategories.Count > 0)
      {
          Console.WriteLine($"Violated Categories: {string.Join(", ", violatedCategories)}");
      }
      if (!string.IsNullOrEmpty(explanation))
      {
          Console.WriteLine($"Explanation: {explanation}");
      }
  }
  ```

  ```go Go
  func assessRiskLevel(message string, unsafeCategories []string) (int, []string, string) {
  	// Wandle die unsicheren Kategorien in einen String um, mit jeder Kategorie in einer neuen Zeile
  	unsafeCategoryStr := strings.Join(unsafeCategories, "\n")

  	// Erstelle den Prompt für Claude, einschließlich der Nachricht, der unsicheren Kategorien und der Risikostufen-Definitionen
  	assessmentPrompt := fmt.Sprintf(`
      Assess the risk level of the following message,
      based on the unsafe categories listed below.

  Message:
  <message>%s</message>

  Unsafe Categories:
  <categories>
  %s
  </categories>

  Assign a risk level based on your confidence that the user's message should be moderated
  based on the defined unsafe categories:

  0 - No risk
  1 - Low risk
  2 - Medium risk
  3 - High risk

  Respond with ONLY a JSON object, using the format below:
  {
    "risk_level": <Numerical field denoting the risk level>,
    "categories": [Comma-separated list of violated categories],
    "explanation": <Optional. Only include if risk level is greater than 0>
  }
  Do not include markdown formatting or code fences in your response.`, message, unsafeCategoryStr)

  	// Sende die Anfrage zur Risikobewertung an Claude
  	response, err := client.Messages.New(context.Background(), anthropic.MessageNewParams{
  		Model:     anthropic.ModelClaudeHaiku4_5_20251001, // Using the Haiku model for lower costs
  		MaxTokens: 200,
  		Messages: []anthropic.MessageParam{
  			anthropic.NewUserMessage(anthropic.NewTextBlock(assessmentPrompt)),
  		},
  	})
  	if err != nil {
  		log.Fatal(err)
  	}

  	// Grenze den ersten Content-Block auf einen Textblock ein, bevor du dessen Text liest
  	textBlock, ok := response.Content[0].AsAny().(anthropic.TextBlock)
  	if !ok {
  		log.Fatalf("expected a text block, got %q", response.Content[0].Type)
  	}

  	// Parse die JSON-Antwort von Claude
  	var assessment struct {
  		RiskLevel   int      `json:"risk_level"`
  		Categories  []string `json:"categories"`
  		Explanation string   `json:"explanation"`
  	}
  	if err := json.Unmarshal([]byte(textBlock.Text), &assessment); err != nil {
  		log.Fatal(err)
  	}

  	// Gib die Risikostufe, die verletzten Kategorien und die Erklärung aus der Bewertung zurück
  	return assessment.RiskLevel, assessment.Categories, assessment.Explanation
  }

  // assessAllRiskLevels verarbeitet jeden Kommentar und gibt die Ergebnisse aus.
  func assessAllRiskLevels() {
  	for _, comment := range userComments {
  		fmt.Printf("\nComment: %s\n", comment)
  		riskLevel, violatedCategories, explanation := assessRiskLevel(comment, unsafeCategories)

  		fmt.Printf("Risk Level: %d\n", riskLevel)
  		if len(violatedCategories) > 0 {
  			fmt.Printf("Violated Categories: %s\n", strings.Join(violatedCategories, ", "))
  		}
  		if explanation != "" {
  			fmt.Printf("Explanation: %s\n", explanation)
  		}
  	}
  }
  ```

  ```java Java
  record RiskAssessment(int riskLevel, List<String> violatedCategories, String explanation) {}

  RiskAssessment assessRiskLevel(String message, List<String> unsafeCategories)
          throws JsonProcessingException {
      // Wandle die unsicheren Kategorien in einen String um, mit jeder Kategorie in einer neuen Zeile
      String unsafeCategoryStr = String.join("\n", unsafeCategories);

      // Erstelle den Prompt für Claude, einschließlich der Nachricht, der unsicheren Kategorien und der Risikostufen-Definitionen
      String assessmentPrompt = """

              Assess the risk level of the following message,
              based on the unsafe categories listed below.

          Message:
          <message>%s</message>

          Unsafe Categories:
          <categories>
          %s
          </categories>

          Assign a risk level based on your confidence that the user's message should be moderated
          based on the defined unsafe categories:

          0 - No risk
          1 - Low risk
          2 - Medium risk
          3 - High risk

          Respond with ONLY a JSON object, using the format below:
          {
            "risk_level": <Numerical field denoting the risk level>,
            "categories": [Comma-separated list of violated categories],
            "explanation": <Optional. Only include if risk level is greater than 0>
          }
          Do not include markdown formatting or code fences in your response."""
              .formatted(message, unsafeCategoryStr);

      // Sende die Anfrage zur Risikobewertung an Claude
      Message response = client.messages().create(MessageCreateParams.builder()
              .model(Model.CLAUDE_HAIKU_4_5_20251001) // Using the Haiku model for lower costs
              .maxTokens(200)
              .addUserMessage(assessmentPrompt)
              .build());

      // Parse die JSON-Antwort von Claude
      String assessmentJson = response.content().stream()
              .flatMap(contentBlock -> contentBlock.text().stream())
              .findFirst()
              .orElseThrow()
              .text();
      ObjectMapper mapper = new ObjectMapper();
      JsonNode assessment = mapper.readTree(assessmentJson);

      // Extrahiere die Risikostufe, die verletzten Kategorien und die Erklärung aus der Bewertung
      int riskLevel = assessment.required("risk_level").asInt();
      JsonNode categoriesNode = assessment.required("categories");
      List<String> violatedCategories = categoriesNode.isNull()
              ? List.of()
              : mapper.convertValue(categoriesNode, new TypeReference<List<String>>() {});
      String explanation = assessment.hasNonNull("explanation")
              ? assessment.get("explanation").asText()
              : null;

      return new RiskAssessment(riskLevel, violatedCategories, explanation);
  }

  // Verarbeite jeden Kommentar und gib die Ergebnisse aus
  void printRiskLevels() throws JsonProcessingException {
      for (String comment : userComments) {
          IO.println("\nComment: " + comment);
          RiskAssessment assessment = assessRiskLevel(comment, unsafeCategories);

          IO.println("Risk Level: " + assessment.riskLevel());
          if (!assessment.violatedCategories().isEmpty()) {
              IO.println("Violated Categories: " + String.join(", ", assessment.violatedCategories()));
          }
          if (assessment.explanation() != null && !assessment.explanation().isEmpty()) {
              IO.println("Explanation: " + assessment.explanation());
          }
      }
  }
  ```

  ```php PHP
  $assessRiskLevel = function (string $message, array $unsafeCategories) use ($client): array {
      // Wandle die unsicheren Kategorien in einen String um, mit jeder Kategorie in einer neuen Zeile
      $unsafeCategoryStr = implode("\n", $unsafeCategories);

      // Erstelle den Prompt für Claude, einschließlich der Nachricht, der unsicheren Kategorien und der Risikostufen-Definitionen
      $assessmentPrompt = <<<PROMPT

          Assess the risk level of the following message,
          based on the unsafe categories listed below.

      Message:
      <message>{$message}</message>

      Unsafe Categories:
      <categories>
      {$unsafeCategoryStr}
      </categories>

      Assign a risk level based on your confidence that the user's message should be moderated
      based on the defined unsafe categories:

      0 - No risk
      1 - Low risk
      2 - Medium risk
      3 - High risk

      Respond with ONLY a JSON object, using the format below:
      {
        "risk_level": <Numerical field denoting the risk level>,
        "categories": [Comma-separated list of violated categories],
        "explanation": <Optional. Only include if risk level is greater than 0>
      }
      Do not include markdown formatting or code fences in your response.
      PROMPT;

      // Sende die Anfrage zur Risikobewertung an Claude
      $response = $client->messages->create(
          model: 'claude-haiku-4-5-20251001', // Using the Haiku model for lower costs
          maxTokens: 200,
          messages: [['role' => 'user', 'content' => $assessmentPrompt]],
      );

      // Parse die JSON-Antwort von Claude. Das SDK dekodiert jeden Content-Block
      // in seine konkrete Klasse, finde also den TextBlock, bevor du den Text liest.
      $textBlock = array_find($response->content, fn ($block) => $block instanceof \Anthropic\Messages\TextBlock)
          ?? throw new \RuntimeException('Expected a text block in the response.');
      $assessment = json_decode($textBlock->text, associative: true, flags: JSON_THROW_ON_ERROR);

      // Extrahiere die Risikostufe, die verletzten Kategorien und die Erklärung aus der Bewertung
      $riskLevel = $assessment['risk_level'];
      $violatedCategories = $assessment['categories'];
      $explanation = $assessment['explanation'] ?? null;

      return [$riskLevel, $violatedCategories, $explanation];
  };

  // Verarbeite jeden Kommentar und gib die Ergebnisse aus
  foreach ($userComments as $comment) {
      echo "\nComment: {$comment}\n";
      [$riskLevel, $violatedCategories, $explanation] = $assessRiskLevel($comment, $unsafeCategories);

      echo "Risk Level: {$riskLevel}\n";
      if ($violatedCategories) {
          echo 'Violated Categories: ' . implode(', ', $violatedCategories) . "\n";
      }
      if ($explanation) {
          echo "Explanation: {$explanation}\n";
      }
  }
  ```

  ```ruby Ruby
  def assess_risk_level(message, unsafe_categories)
    # Wandle die unsicheren Kategorien in einen String um, mit jeder Kategorie in einer neuen Zeile
    unsafe_category_str = unsafe_categories.join("\n")

    # Erstelle den Prompt für Claude, einschließlich der Nachricht, der unsicheren Kategorien und der Risikostufen-Definitionen
    assessment_prompt = <<~PROMPT.chomp

          Assess the risk level of the following message,
          based on the unsafe categories listed below.

      Message:
      <message>#{message}</message>

      Unsafe Categories:
      <categories>
      #{unsafe_category_str}
      </categories>

      Assign a risk level based on your confidence that the user's message should be moderated
      based on the defined unsafe categories:

      0 - No risk
      1 - Low risk
      2 - Medium risk
      3 - High risk

      Respond with ONLY a JSON object, using the format below:
      {
        "risk_level": <Numerical field denoting the risk level>,
        "categories": [Comma-separated list of violated categories],
        "explanation": <Optional. Only include if risk level is greater than 0>
      }
      Do not include markdown formatting or code fences in your response.
    PROMPT

    # Sende die Anfrage zur Risikobewertung an Claude
    response = CLIENT.messages.create(
      model: "claude-haiku-4-5-20251001", # Using the Haiku model for lower costs
      max_tokens: 200,
      messages: [{role: :user, content: assessment_prompt}]
    )

    # Parse die JSON-Antwort von Claude
    text_block = response.content.find { it.type == :text }
    assessment = JSON.parse(text_block.text)

    # Extrahiere die Risikostufe, die verletzten Kategorien und die Erklärung aus der Bewertung
    risk_level = assessment["risk_level"]
    violated_categories = assessment["categories"]
    explanation = assessment["explanation"]

    [risk_level, violated_categories, explanation]
  end


  # Verarbeite jeden Kommentar und gib die Ergebnisse aus
  USER_COMMENTS.each do |comment|
    puts "\nComment: #{comment}"
    risk_level, violated_categories, explanation = assess_risk_level(comment, UNSAFE_CATEGORIES)

    puts "Risk Level: #{risk_level}"
    puts "Violated Categories: #{violated_categories.join(", ")}" if violated_categories&.any?
    puts "Explanation: #{explanation}" if explanation
  end
  ```
</CodeGroup>

Dieser Code implementiert eine Funktion `assess_risk_level`, die Claude verwendet, um die Risikostufe einer Nachricht zu bewerten. Die Funktion nimmt eine Nachricht und die unsicheren Kategorien als Eingaben entgegen.

Innerhalb der Funktion wird ein Prompt für Claude generiert, der die zu bewertende Nachricht, die unsicheren Kategorien und spezifische Anweisungen zur Bewertung der Risikostufe enthält. Der Prompt weist Claude an, mit einem JSON-Objekt zu antworten, das die Risikostufe, die verletzten Kategorien und eine optionale Erklärung enthält.

Dieser Ansatz ermöglicht eine flexible Inhaltsmoderation durch die Zuweisung von Risikostufen. Er lässt sich nahtlos in ein größeres System integrieren, um die Inhaltsfilterung zu automatisieren oder Kommentare basierend auf ihrer bewerteten Risikostufe zur menschlichen Überprüfung zu kennzeichnen. Beim Ausführen dieses Codes wird beispielsweise der Kommentar `Delete this post now or you better hide. I am coming after you and your family.` aufgrund seiner gefährlichen Drohung als hohes Risiko eingestuft. Umgekehrt wird der Kommentar `Stay away from the 5G cellphones!! They are using 5G to control you.` als mittleres Risiko kategorisiert.

### Stelle deinen Prompt bereit

Sobald du von der Qualität deiner Lösung überzeugt bist, ist es Zeit, sie in der Produktion bereitzustellen. Hier sind einige Best Practices, die du beim Einsatz von Inhaltsmoderation in der Produktion befolgen solltest:

1. **Gib Nutzern klares Feedback:** Wenn eine Nutzereingabe blockiert oder eine Antwort aufgrund der Inhaltsmoderation gekennzeichnet wird, gib informatives und konstruktives Feedback, damit Nutzer verstehen, warum ihre Nachricht gekennzeichnet wurde und wie sie sie angemessen umformulieren können. In den vorherigen Codebeispielen geschieht dies über das Feld `explanation` in der Claude-Antwort.

2. **Analysiere moderierte Inhalte:** Behalte im Blick, welche Arten von Inhalten von deinem Moderationssystem gekennzeichnet werden, um Trends und potenzielle Verbesserungsbereiche zu identifizieren.

3. **Evaluiere und verbessere kontinuierlich:** Bewerte regelmäßig die Leistung deines Inhaltsmoderationssystems anhand von Metriken wie Precision- und Recall-Tracking. Nutze diese Daten, um deine Moderations-Prompts, Schlüsselwörter und Bewertungskriterien iterativ zu verfeinern.

***

## Leistung verbessern

In komplexen Szenarien kann es hilfreich sein, über die standardmäßigen [Prompt-Engineering-Techniken](https://platform.claude.com/docs/de/build-with-claude/prompt-engineering/overview) hinaus zusätzliche Strategien zur Leistungsverbesserung in Betracht zu ziehen. Hier sind einige fortgeschrittene Strategien:

### Definiere Themen und stelle Beispiele bereit

Zusätzlich zur Auflistung der unsicheren Kategorien im Prompt lassen sich weitere Verbesserungen erzielen, indem Definitionen und Formulierungen zu jeder Kategorie bereitgestellt werden.

<CodeGroup exclude="shell">
  ```python Python
  # Kategorien, die für die Content-Moderation als unsicher gelten, mit ihren Definitionen
  unsafe_category_definitions = {
      "Child Exploitation": "Content that depicts child nudity or that enables, encourages, excuses, or depicts the sexual abuse of children.",
      "Conspiracy Theories": """Content that promotes or endorses unfounded, false, or misleading theories about events, situations, or individuals,
          which can incite harm or undermine public trust in institutions or facts.""",
      "Hate": """Content that is hateful toward people on the basis of their protected characteristics
          (race, color, ethnicity, national origin, disability, religious affiliation, caste, sexual orientation, sex, gender identity and serious disease),
          or content that perpetuates negative stereotypes.""",
      "Indiscriminate Weapons": "Content that enables the creation of weapons of mass destruction.",
      "Intellectual Property": "Content that violates the intellectual property rights of third parties.",
      "Non-Violent Crimes": "Content that enables, encourages, or excuses the commission of non-violent crimes.",
      "Privacy": "Content that contains sensitive, personal information about private individuals.",
      "Self-Harm": "Content that enables, encourages, or excuses acts of intentional self-harm.",
      "Sex Crimes": "Content that enables, encourages, or excuses the commission of sex crimes.",
      "Sexual Content": "Content that contains erotic descriptions or explicit depictions of sex acts.",
      "Specialized Advice": """Content that contains financial, medical, or legal advice.
          Financial advice includes guidance on investments, stocks, bonds, or any financial planning.""",
      "Violent Crimes": "Content that enables, encourages, or excuses the commission of violent crimes.",
  }


  def moderate_message_with_definitions(message, unsafe_category_definitions):
      # Formatiere den String der unsicheren Kategorien, mit jeder Kategorie und ihrer Definition in einer neuen Zeile
      unsafe_category_str = "\n".join(
          f"{category}: {definition}"
          for category, definition in unsafe_category_definitions.items()
      )

      # Erstelle den Prompt für Claude, einschließlich der Nachricht und der unsicheren Kategorien
      assessment_prompt = f"""Determine whether the following message warrants moderation, based on the unsafe categories outlined below.

  Message:
  <message>{message}</message>

  Unsafe Categories and Their Definitions:
  <categories>
  {unsafe_category_str}
  </categories>

  It's important that you remember all unsafe categories and their definitions.

  Respond with ONLY a JSON object, using the format below:
  {{
    "violation": <Boolean field denoting whether the message should be moderated>,
    "categories": [Comma-separated list of violated categories],
    "explanation": [Optional. Only include if there is a violation.]
  }}
  Do not include markdown formatting or code fences in your response."""

      # Sende die Anfrage zur Content-Moderation an Claude
      response = client.messages.create(
          model="claude-haiku-4-5-20251001",  # Using the Haiku model for lower costs
          max_tokens=200,
          messages=[{"role": "user", "content": assessment_prompt}],
      )

      # Parse die JSON-Antwort von Claude
      text_block = next(block for block in response.content if block.type == "text")
      assessment = json.loads(text_block.text)

      # Extrahiere den Verstoß-Status aus der Bewertung
      contains_violation = assessment["violation"]

      # Bei einem Verstoß hole die Kategorien und die Erklärung; andernfalls verwende leere Standardwerte
      violated_categories = assessment.get("categories", []) if contains_violation else []
      explanation = assessment.get("explanation") if contains_violation else None

      return contains_violation, violated_categories, explanation


  # Verarbeite jeden Kommentar und gib die Ergebnisse aus
  for comment in user_comments:
      print(f"\nComment: {comment}")
      violation, violated_categories, explanation = moderate_message_with_definitions(
          comment, unsafe_category_definitions
      )

      if violation:
          print(f"Violated Categories: {', '.join(violated_categories)}")
          print(f"Explanation: {explanation}")
      else:
          print("No issues detected.")
  ```

  ```typescript TypeScript
  // Struktur der JSON-Bewertung, die Claude zurückgibt
  interface DefinitionBasedAssessment {
    violation: boolean;
    categories?: string[];
    explanation?: string;
  }

  // Kategorien, die für die Content-Moderation als unsicher gelten, mit ihren Definitionen
  // (Objekt-Keys behalten die Einfügereihenfolge, daher erscheinen die Kategorien in dieser Reihenfolge)
  const unsafeCategoryDefinitions: Record<string, string> = {
    "Child Exploitation":
      "Content that depicts child nudity or that enables, encourages, excuses, or depicts the sexual abuse of children.",
    "Conspiracy Theories": `Content that promotes or endorses unfounded, false, or misleading theories about events, situations, or individuals,
          which can incite harm or undermine public trust in institutions or facts.`,
    Hate: `Content that is hateful toward people on the basis of their protected characteristics
          (race, color, ethnicity, national origin, disability, religious affiliation, caste, sexual orientation, sex, gender identity and serious disease),
          or content that perpetuates negative stereotypes.`,
    "Indiscriminate Weapons":
      "Content that enables the creation of weapons of mass destruction.",
    "Intellectual Property":
      "Content that violates the intellectual property rights of third parties.",
    "Non-Violent Crimes":
      "Content that enables, encourages, or excuses the commission of non-violent crimes.",
    Privacy: "Content that contains sensitive, personal information about private individuals.",
    "Self-Harm": "Content that enables, encourages, or excuses acts of intentional self-harm.",
    "Sex Crimes": "Content that enables, encourages, or excuses the commission of sex crimes.",
    "Sexual Content":
      "Content that contains erotic descriptions or explicit depictions of sex acts.",
    "Specialized Advice": `Content that contains financial, medical, or legal advice.
          Financial advice includes guidance on investments, stocks, bonds, or any financial planning.`,
    "Violent Crimes":
      "Content that enables, encourages, or excuses the commission of violent crimes."
  };

  async function moderateMessageWithDefinitions(
    message: string,
    unsafeCategoryDefinitions: Record<string, string>
  ): Promise<{ violation: boolean; violatedCategories: string[]; explanation?: string }> {
    // Formatiere den String der unsicheren Kategorien, mit jeder Kategorie und ihrer Definition in einer neuen Zeile
    const unsafeCategoryStr = Object.entries(unsafeCategoryDefinitions)
      .map(([category, definition]) => `${category}: ${definition}`)
      .join("\n");

    // Erstelle den Prompt für Claude, einschließlich der Nachricht und der unsicheren Kategorien
    const assessmentPrompt = `Determine whether the following message warrants moderation, based on the unsafe categories outlined below.

  Message:
  <message>${message}</message>

  Unsafe Categories and Their Definitions:
  <categories>
  ${unsafeCategoryStr}
  </categories>

  It's important that you remember all unsafe categories and their definitions.

  Respond with ONLY a JSON object, using the format below:
  {
    "violation": <Boolean field denoting whether the message should be moderated>,
    "categories": [Comma-separated list of violated categories],
    "explanation": [Optional. Only include if there is a violation.]
  }
  Do not include markdown formatting or code fences in your response.`;

    // Sende die Anfrage zur Content-Moderation an Claude
    const response = await client.messages.create({
      model: "claude-haiku-4-5-20251001", // Using the Haiku model for lower costs
      max_tokens: 200,
      messages: [{ role: "user", content: assessmentPrompt }]
    });

    // Parse die JSON-Antwort von Claude
    const textBlock = response.content.find((block) => block.type === "text");
    if (!textBlock) {
      throw new Error("Expected a text block in the response");
    }
    const assessment: DefinitionBasedAssessment = JSON.parse(textBlock.text);

    // Extrahiere den Verstoß-Status aus der Bewertung
    const containsViolation = assessment.violation;

    // Bei einem Verstoß hole die Kategorien und die Erklärung; andernfalls verwende leere Standardwerte
    const violatedCategories = containsViolation ? (assessment.categories ?? []) : [];
    const explanation = containsViolation ? assessment.explanation : undefined;

    return { violation: containsViolation, violatedCategories, explanation };
  }

  // Verarbeite jeden Kommentar und gib die Ergebnisse aus
  for (const comment of userComments) {
    console.log(`\nComment: ${comment}`);
    const { violation, violatedCategories, explanation } = await moderateMessageWithDefinitions(
      comment,
      unsafeCategoryDefinitions
    );

    if (violation) {
      console.log(`Violated Categories: ${violatedCategories.join(", ")}`);
      console.log(`Explanation: ${explanation}`);
    } else {
      console.log("No issues detected.");
    }
  }
  ```

  ```csharp C#
  // Kategorien, die für die Content-Moderation als unsicher gelten, mit ihren Definitionen.
  // Die Einträge bleiben in Einfügereihenfolge, daher listet der gerenderte Prompt die Kategorien
  // genau in dieser Reihenfolge auf.
  (string Category, string Definition)[] unsafeCategoryDefinitions =
  [
      (
          "Child Exploitation",
          "Content that depicts child nudity or that enables, encourages, excuses, or depicts the sexual abuse of children."
      ),
      (
          "Conspiracy Theories",
          """
          Content that promotes or endorses unfounded, false, or misleading theories about events, situations, or individuals,
                  which can incite harm or undermine public trust in institutions or facts.
          """
      ),
      (
          "Hate",
          """
          Content that is hateful toward people on the basis of their protected characteristics
                  (race, color, ethnicity, national origin, disability, religious affiliation, caste, sexual orientation, sex, gender identity and serious disease),
                  or content that perpetuates negative stereotypes.
          """
      ),
      ("Indiscriminate Weapons", "Content that enables the creation of weapons of mass destruction."),
      ("Intellectual Property", "Content that violates the intellectual property rights of third parties."),
      ("Non-Violent Crimes", "Content that enables, encourages, or excuses the commission of non-violent crimes."),
      ("Privacy", "Content that contains sensitive, personal information about private individuals."),
      ("Self-Harm", "Content that enables, encourages, or excuses acts of intentional self-harm."),
      ("Sex Crimes", "Content that enables, encourages, or excuses the commission of sex crimes."),
      ("Sexual Content", "Content that contains erotic descriptions or explicit depictions of sex acts."),
      (
          "Specialized Advice",
          """
          Content that contains financial, medical, or legal advice.
                  Financial advice includes guidance on investments, stocks, bonds, or any financial planning.
          """
      ),
      ("Violent Crimes", "Content that enables, encourages, or excuses the commission of violent crimes."),
  ];


  async Task<(bool ContainsViolation, List<string> ViolatedCategories, string? Explanation)> ModerateMessageWithDefinitions(
      string message,
      IReadOnlyList<(string Category, string Definition)> categoryDefinitions
  )
  {
      // Formatiere den String der unsicheren Kategorien, mit jeder Kategorie und ihrer Definition in einer neuen Zeile
      var unsafeCategoryText = string.Join(
          "\n",
          categoryDefinitions.Select(entry => $"{entry.Category}: {entry.Definition}")
      );

      // Erstelle den Prompt für Claude, einschließlich der Nachricht und der unsicheren Kategorien
      var assessmentPrompt = $$"""
  Determine whether the following message warrants moderation, based on the unsafe categories outlined below.

  Message:
  <message>{{message}}</message>

  Unsafe Categories and Their Definitions:
  <categories>
  {{unsafeCategoryText}}
  </categories>

  It's important that you remember all unsafe categories and their definitions.

  Respond with ONLY a JSON object, using the format below:
  {
    "violation": <Boolean field denoting whether the message should be moderated>,
    "categories": [Comma-separated list of violated categories],
    "explanation": [Optional. Only include if there is a violation.]
  }
  Do not include markdown formatting or code fences in your response.
  """;

      // Sende die Anfrage zur Content-Moderation an Claude
      var response = await client.Messages.Create(
          new()
          {
              Model = Model.ClaudeHaiku4_5_20251001, // Using the Haiku model for lower costs
              MaxTokens = 200,
              Messages = [new() { Role = Role.User, Content = assessmentPrompt }],
          }
      );

      // Grenze den ersten Content-Block auf einen Textblock ein und parse dann Claudes JSON-Antwort
      if (!response.Content[0].TryPickText(out var textBlock))
      {
          throw new InvalidOperationException("Expected a text response from Claude.");
      }
      var assessment = JsonNode.Parse(textBlock.Text)!;

      // Extrahiere den Verstoß-Status aus der Bewertung
      var containsViolation = assessment["violation"]!.GetValue<bool>();

      // Bei einem Verstoß hole die Kategorien und die Erklärung; andernfalls verwende leere Standardwerte
      List<string> violatedCategories = containsViolation
          ? assessment["categories"]?.AsArray().Select(category => category!.GetValue<string>()).ToList() ?? []
          : [];
      var explanation = containsViolation ? assessment["explanation"]?.GetValue<string>() : null;

      return (containsViolation, violatedCategories, explanation);
  }

  // Verarbeite jeden Kommentar und gib die Ergebnisse aus
  foreach (var comment in userComments)
  {
      Console.WriteLine($"\nComment: {comment}");
      var (violation, violatedCategories, explanation) = await ModerateMessageWithDefinitions(
          comment,
          unsafeCategoryDefinitions
      );

      if (violation)
      {
          Console.WriteLine($"Violated Categories: {string.Join(", ", violatedCategories)}");
          Console.WriteLine($"Explanation: {explanation}");
      }
      else
      {
          Console.WriteLine("No issues detected.");
      }
  }
  ```

  ```go Go
  // Kategorien, die für die Content-Moderation als unsicher gelten, mit ihren Definitionen.
  // Ein Slice aus Kategorie/Definition-Paaren (statt einer Map) hält die gerenderte
  // Reihenfolge stabil; Go-Maps iterieren in zufälliger Reihenfolge.
  type categoryDefinition struct {
  	category   string
  	definition string
  }

  var unsafeCategoryDefinitions = []categoryDefinition{
  	{"Child Exploitation", "Content that depicts child nudity or that enables, encourages, excuses, or depicts the sexual abuse of children."},
  	{"Conspiracy Theories", `Content that promotes or endorses unfounded, false, or misleading theories about events, situations, or individuals,
          which can incite harm or undermine public trust in institutions or facts.`},
  	{"Hate", `Content that is hateful toward people on the basis of their protected characteristics
          (race, color, ethnicity, national origin, disability, religious affiliation, caste, sexual orientation, sex, gender identity and serious disease),
          or content that perpetuates negative stereotypes.`},
  	{"Indiscriminate Weapons", "Content that enables the creation of weapons of mass destruction."},
  	{"Intellectual Property", "Content that violates the intellectual property rights of third parties."},
  	{"Non-Violent Crimes", "Content that enables, encourages, or excuses the commission of non-violent crimes."},
  	{"Privacy", "Content that contains sensitive, personal information about private individuals."},
  	{"Self-Harm", "Content that enables, encourages, or excuses acts of intentional self-harm."},
  	{"Sex Crimes", "Content that enables, encourages, or excuses the commission of sex crimes."},
  	{"Sexual Content", "Content that contains erotic descriptions or explicit depictions of sex acts."},
  	{"Specialized Advice", `Content that contains financial, medical, or legal advice.
          Financial advice includes guidance on investments, stocks, bonds, or any financial planning.`},
  	{"Violent Crimes", "Content that enables, encourages, or excuses the commission of violent crimes."},
  }

  func moderateMessageWithDefinitions(message string, unsafeCategoryDefinitions []categoryDefinition) (bool, []string, string) {
  	// Formatiere den String der unsicheren Kategorien, mit jeder Kategorie und ihrer Definition in einer neuen Zeile
  	categoryLines := make([]string, len(unsafeCategoryDefinitions))
  	for i, entry := range unsafeCategoryDefinitions {
  		categoryLines[i] = fmt.Sprintf("%s: %s", entry.category, entry.definition)
  	}
  	unsafeCategoryStr := strings.Join(categoryLines, "\n")

  	// Erstelle den Prompt für Claude, einschließlich der Nachricht und der unsicheren Kategorien
  	assessmentPrompt := fmt.Sprintf(`Determine whether the following message warrants moderation, based on the unsafe categories outlined below.

  Message:
  <message>%s</message>

  Unsafe Categories and Their Definitions:
  <categories>
  %s
  </categories>

  It's important that you remember all unsafe categories and their definitions.

  Respond with ONLY a JSON object, using the format below:
  {
    "violation": <Boolean field denoting whether the message should be moderated>,
    "categories": [Comma-separated list of violated categories],
    "explanation": [Optional. Only include if there is a violation.]
  }
  Do not include markdown formatting or code fences in your response.`, message, unsafeCategoryStr)

  	// Sende die Anfrage zur Content-Moderation an Claude
  	response, err := client.Messages.New(context.Background(), anthropic.MessageNewParams{
  		Model:     anthropic.ModelClaudeHaiku4_5_20251001, // Using the Haiku model for lower costs
  		MaxTokens: 200,
  		Messages: []anthropic.MessageParam{
  			anthropic.NewUserMessage(anthropic.NewTextBlock(assessmentPrompt)),
  		},
  	})
  	if err != nil {
  		log.Fatal(err)
  	}

  	// Grenze den ersten Content-Block auf einen Textblock ein, bevor du dessen Text liest
  	textBlock, ok := response.Content[0].AsAny().(anthropic.TextBlock)
  	if !ok {
  		log.Fatalf("expected a text block, got %q", response.Content[0].Type)
  	}

  	// Parse die JSON-Antwort von Claude
  	var assessment struct {
  		Violation   bool     `json:"violation"`
  		Categories  []string `json:"categories"`
  		Explanation string   `json:"explanation"`
  	}
  	if err := json.Unmarshal([]byte(textBlock.Text), &assessment); err != nil {
  		log.Fatal(err)
  	}

  	// Bei einem Verstoß gib die Kategorien und die Erklärung zurück; andernfalls verwende leere Standardwerte
  	if !assessment.Violation {
  		return false, nil, ""
  	}
  	return true, assessment.Categories, assessment.Explanation
  }

  // moderateAllCommentsWithDefinitions verarbeitet jeden Kommentar und gibt die Ergebnisse aus.
  func moderateAllCommentsWithDefinitions() {
  	for _, comment := range userComments {
  		fmt.Printf("\nComment: %s\n", comment)
  		violation, violatedCategories, explanation := moderateMessageWithDefinitions(comment, unsafeCategoryDefinitions)

  		if violation {
  			fmt.Printf("Violated Categories: %s\n", strings.Join(violatedCategories, ", "))
  			fmt.Printf("Explanation: %s\n", explanation)
  		} else {
  			fmt.Println("No issues detected.")
  		}
  	}
  }
  ```

  ```java Java
  // Kategorien, die für die Content-Moderation als unsicher gelten, mit ihren Definitionen
  record CategoryDefinition(String category, String definition) {}

  final List<CategoryDefinition> unsafeCategoryDefinitions = List.of(
          new CategoryDefinition(
                  "Child Exploitation",
                  "Content that depicts child nudity or that enables, encourages, excuses, or depicts the sexual abuse of children."),
          new CategoryDefinition(
                  "Conspiracy Theories",
                  """
                  Content that promotes or endorses unfounded, false, or misleading theories about events, situations, or individuals,
                          which can incite harm or undermine public trust in institutions or facts."""),
          new CategoryDefinition(
                  "Hate",
                  """
                  Content that is hateful toward people on the basis of their protected characteristics
                          (race, color, ethnicity, national origin, disability, religious affiliation, caste, sexual orientation, sex, gender identity and serious disease),
                          or content that perpetuates negative stereotypes."""),
          new CategoryDefinition(
                  "Indiscriminate Weapons",
                  "Content that enables the creation of weapons of mass destruction."),
          new CategoryDefinition(
                  "Intellectual Property",
                  "Content that violates the intellectual property rights of third parties."),
          new CategoryDefinition(
                  "Non-Violent Crimes",
                  "Content that enables, encourages, or excuses the commission of non-violent crimes."),
          new CategoryDefinition(
                  "Privacy",
                  "Content that contains sensitive, personal information about private individuals."),
          new CategoryDefinition(
                  "Self-Harm",
                  "Content that enables, encourages, or excuses acts of intentional self-harm."),
          new CategoryDefinition(
                  "Sex Crimes",
                  "Content that enables, encourages, or excuses the commission of sex crimes."),
          new CategoryDefinition(
                  "Sexual Content",
                  "Content that contains erotic descriptions or explicit depictions of sex acts."),
          new CategoryDefinition(
                  "Specialized Advice",
                  """
                  Content that contains financial, medical, or legal advice.
                          Financial advice includes guidance on investments, stocks, bonds, or any financial planning."""),
          new CategoryDefinition(
                  "Violent Crimes",
                  "Content that enables, encourages, or excuses the commission of violent crimes."));

  record ModerationDecision(boolean violation, List<String> violatedCategories, String explanation) {}

  ModerationDecision moderateMessageWithDefinitions(
          String message, List<CategoryDefinition> unsafeCategoryDefinitions)
          throws JsonProcessingException {
      // Formatiere den String der unsicheren Kategorien, mit jeder Kategorie und ihrer Definition in einer neuen Zeile
      String unsafeCategoryStr = unsafeCategoryDefinitions.stream()
              .map(categoryDefinition ->
                      categoryDefinition.category() + ": " + categoryDefinition.definition())
              .collect(Collectors.joining("\n"));

      // Erstelle den Prompt für Claude, einschließlich der Nachricht und der unsicheren Kategorien
      String assessmentPrompt = """
          Determine whether the following message warrants moderation, based on the unsafe categories outlined below.

          Message:
          <message>%s</message>

          Unsafe Categories and Their Definitions:
          <categories>
          %s
          </categories>

          It's important that you remember all unsafe categories and their definitions.

          Respond with ONLY a JSON object, using the format below:
          {
            "violation": <Boolean field denoting whether the message should be moderated>,
            "categories": [Comma-separated list of violated categories],
            "explanation": [Optional. Only include if there is a violation.]
          }
          Do not include markdown formatting or code fences in your response."""
              .formatted(message, unsafeCategoryStr);

      // Sende die Anfrage zur Content-Moderation an Claude
      Message response = client.messages().create(MessageCreateParams.builder()
              .model(Model.CLAUDE_HAIKU_4_5_20251001) // Using the Haiku model for lower costs
              .maxTokens(200)
              .addUserMessage(assessmentPrompt)
              .build());

      // Parse die JSON-Antwort von Claude
      String assessmentJson = response.content().stream()
              .flatMap(contentBlock -> contentBlock.text().stream())
              .findFirst()
              .orElseThrow()
              .text();
      ObjectMapper mapper = new ObjectMapper();
      JsonNode assessment = mapper.readTree(assessmentJson);

      // Extrahiere den Verstoß-Status aus der Bewertung
      boolean containsViolation = assessment.required("violation").asBoolean();

      // Bei einem Verstoß hole die Kategorien und die Erklärung; andernfalls verwende leere Standardwerte
      List<String> violatedCategories = containsViolation && assessment.has("categories")
              ? mapper.convertValue(assessment.get("categories"), new TypeReference<List<String>>() {})
              : List.of();
      String explanation = containsViolation && assessment.hasNonNull("explanation")
              ? assessment.get("explanation").asText()
              : null;

      return new ModerationDecision(containsViolation, violatedCategories, explanation);
  }

  // Verarbeite jeden Kommentar und gib die Ergebnisse aus
  void printModerationResultsWithDefinitions() throws JsonProcessingException {
      for (String comment : userComments) {
          IO.println("\nComment: " + comment);
          ModerationDecision result = moderateMessageWithDefinitions(comment, unsafeCategoryDefinitions);

          if (result.violation()) {
              IO.println("Violated Categories: " + String.join(", ", result.violatedCategories()));
              IO.println("Explanation: " + result.explanation());
          } else {
              IO.println("No issues detected.");
          }
      }
  }
  ```

  ```php PHP
  // Kategorien, die für die Content-Moderation als unsicher gelten, mit ihren Definitionen
  $unsafeCategoryDefinitions = [
      'Child Exploitation' => 'Content that depicts child nudity or that enables, encourages, excuses, or depicts the sexual abuse of children.',
      'Conspiracy Theories' => 'Content that promotes or endorses unfounded, false, or misleading theories about events, situations, or individuals,
          which can incite harm or undermine public trust in institutions or facts.',
      'Hate' => 'Content that is hateful toward people on the basis of their protected characteristics
          (race, color, ethnicity, national origin, disability, religious affiliation, caste, sexual orientation, sex, gender identity and serious disease),
          or content that perpetuates negative stereotypes.',
      'Indiscriminate Weapons' => 'Content that enables the creation of weapons of mass destruction.',
      'Intellectual Property' => 'Content that violates the intellectual property rights of third parties.',
      'Non-Violent Crimes' => 'Content that enables, encourages, or excuses the commission of non-violent crimes.',
      'Privacy' => 'Content that contains sensitive, personal information about private individuals.',
      'Self-Harm' => 'Content that enables, encourages, or excuses acts of intentional self-harm.',
      'Sex Crimes' => 'Content that enables, encourages, or excuses the commission of sex crimes.',
      'Sexual Content' => 'Content that contains erotic descriptions or explicit depictions of sex acts.',
      'Specialized Advice' => 'Content that contains financial, medical, or legal advice.
          Financial advice includes guidance on investments, stocks, bonds, or any financial planning.',
      'Violent Crimes' => 'Content that enables, encourages, or excuses the commission of violent crimes.',
  ];

  $moderateMessageWithDefinitions = function (string $message, array $unsafeCategoryDefinitions) use ($client): array {
      // Formatiere den String der unsicheren Kategorien, mit jeder Kategorie und ihrer Definition in einer neuen Zeile
      $categoryLines = [];
      foreach ($unsafeCategoryDefinitions as $category => $definition) {
          $categoryLines[] = "{$category}: {$definition}";
      }
      $unsafeCategoryStr = implode("\n", $categoryLines);

      // Erstelle den Prompt für Claude, einschließlich der Nachricht und der unsicheren Kategorien
      $assessmentPrompt = <<<PROMPT
      Determine whether the following message warrants moderation, based on the unsafe categories outlined below.

      Message:
      <message>{$message}</message>

      Unsafe Categories and Their Definitions:
      <categories>
      {$unsafeCategoryStr}
      </categories>

      It's important that you remember all unsafe categories and their definitions.

      Respond with ONLY a JSON object, using the format below:
      {
        "violation": <Boolean field denoting whether the message should be moderated>,
        "categories": [Comma-separated list of violated categories],
        "explanation": [Optional. Only include if there is a violation.]
      }
      Do not include markdown formatting or code fences in your response.
      PROMPT;

      // Sende die Anfrage zur Content-Moderation an Claude
      $response = $client->messages->create(
          model: 'claude-haiku-4-5-20251001', // Using the Haiku model for lower costs
          maxTokens: 200,
          messages: [['role' => 'user', 'content' => $assessmentPrompt]],
      );

      // Parse die JSON-Antwort von Claude. Das SDK dekodiert jeden Content-Block
      // in seine konkrete Klasse, finde also den TextBlock, bevor du den Text liest.
      $textBlock = array_find($response->content, fn ($block) => $block instanceof \Anthropic\Messages\TextBlock)
          ?? throw new \RuntimeException('Expected a text block in the response.');
      $assessment = json_decode($textBlock->text, associative: true, flags: JSON_THROW_ON_ERROR);

      // Extrahiere den Verstoß-Status aus der Bewertung
      $containsViolation = $assessment['violation'];

      // Bei einem Verstoß hole die Kategorien und die Erklärung; andernfalls verwende leere Standardwerte
      $violatedCategories = $containsViolation ? ($assessment['categories'] ?? []) : [];
      $explanation = $containsViolation ? ($assessment['explanation'] ?? null) : null;

      return [$containsViolation, $violatedCategories, $explanation];
  };

  // Verarbeite jeden Kommentar und gib die Ergebnisse aus
  foreach ($userComments as $comment) {
      echo "\nComment: {$comment}\n";
      [$violation, $violatedCategories, $explanation] = $moderateMessageWithDefinitions($comment, $unsafeCategoryDefinitions);

      if ($violation) {
          echo 'Violated Categories: ' . implode(', ', $violatedCategories) . "\n";
          echo "Explanation: {$explanation}\n";
      } else {
          echo "No issues detected.\n";
      }
  }
  ```

  ```ruby Ruby
  # Kategorien, die für die Content-Moderation als unsicher gelten, mit ihren Definitionen
  UNSAFE_CATEGORY_DEFINITIONS = {
    "Child Exploitation" => "Content that depicts child nudity or that enables, encourages, excuses, or depicts the sexual abuse of children.",
    "Conspiracy Theories" => "Content that promotes or endorses unfounded, false, or misleading theories about events, situations, or individuals,
          which can incite harm or undermine public trust in institutions or facts.",
    "Hate" => "Content that is hateful toward people on the basis of their protected characteristics
          (race, color, ethnicity, national origin, disability, religious affiliation, caste, sexual orientation, sex, gender identity and serious disease),
          or content that perpetuates negative stereotypes.",
    "Indiscriminate Weapons" => "Content that enables the creation of weapons of mass destruction.",
    "Intellectual Property" => "Content that violates the intellectual property rights of third parties.",
    "Non-Violent Crimes" => "Content that enables, encourages, or excuses the commission of non-violent crimes.",
    "Privacy" => "Content that contains sensitive, personal information about private individuals.",
    "Self-Harm" => "Content that enables, encourages, or excuses acts of intentional self-harm.",
    "Sex Crimes" => "Content that enables, encourages, or excuses the commission of sex crimes.",
    "Sexual Content" => "Content that contains erotic descriptions or explicit depictions of sex acts.",
    "Specialized Advice" => "Content that contains financial, medical, or legal advice.
          Financial advice includes guidance on investments, stocks, bonds, or any financial planning.",
    "Violent Crimes" => "Content that enables, encourages, or excuses the commission of violent crimes."
  }


  def moderate_message_with_definitions(message, unsafe_category_definitions)
    # Formatiere den String der unsicheren Kategorien, mit jeder Kategorie und ihrer Definition in einer neuen Zeile
    unsafe_category_str = unsafe_category_definitions
      .map { |category, definition| "#{category}: #{definition}" }
      .join("\n")

    # Erstelle den Prompt für Claude, einschließlich der Nachricht und der unsicheren Kategorien
    assessment_prompt = <<~PROMPT.chomp
      Determine whether the following message warrants moderation, based on the unsafe categories outlined below.

      Message:
      <message>#{message}</message>

      Unsafe Categories and Their Definitions:
      <categories>
      #{unsafe_category_str}
      </categories>

      It's important that you remember all unsafe categories and their definitions.

      Respond with ONLY a JSON object, using the format below:
      {
        "violation": <Boolean field denoting whether the message should be moderated>,
        "categories": [Comma-separated list of violated categories],
        "explanation": [Optional. Only include if there is a violation.]
      }
      Do not include markdown formatting or code fences in your response.
    PROMPT

    # Sende die Anfrage zur Content-Moderation an Claude
    response = CLIENT.messages.create(
      model: "claude-haiku-4-5-20251001", # Using the Haiku model for lower costs
      max_tokens: 200,
      messages: [{role: :user, content: assessment_prompt}]
    )

    # Parse die JSON-Antwort von Claude
    text_block = response.content.find { it.type == :text }
    assessment = JSON.parse(text_block.text)

    # Extrahiere den Verstoß-Status aus der Bewertung
    contains_violation = assessment["violation"]

    # Wenn ein Verstoß vorliegt, hole die Kategorien und die Erklärung; andernfalls verwende leere Standardwerte
    violated_categories = contains_violation ? assessment.fetch("categories", []) : []
    explanation = contains_violation ? assessment["explanation"] : nil

    [contains_violation, violated_categories, explanation]
  end


  # Verarbeite jeden Kommentar und gib die Ergebnisse aus
  USER_COMMENTS.each do |comment|
    puts "\nComment: #{comment}"
    violation, violated_categories, explanation = moderate_message_with_definitions(comment, UNSAFE_CATEGORY_DEFINITIONS)

    if violation
      puts "Violated Categories: #{violated_categories.join(", ")}"
      puts "Explanation: #{explanation}"
    else
      puts "No issues detected."
    end
  end
  ```
</CodeGroup>

Die Funktion `moderate_message_with_definitions` erweitert die frühere Funktion `moderate_message`, indem sie es ermöglicht, jede unsichere Kategorie mit einer detaillierten Definition zu verknüpfen. Im Code geschieht dies, indem die Sammlung `unsafe_categories` aus der ursprünglichen Funktion durch ein Mapping `unsafe_category_definitions` ersetzt wird. Dieses Mapping ordnet jeder unsicheren Kategorie ihre entsprechende Definition zu. Sowohl die Kategorienamen als auch ihre Definitionen werden in den Prompt aufgenommen.

Bemerkenswert ist, dass die Definition der Kategorie `Specialized Advice` nun die Arten von Finanzberatung spezifiziert, die verboten sein sollten. Infolgedessen löst der Kommentar `It is a great time to invest in gold!`, der zuvor die Bewertung durch `moderate_message` bestanden hat, nun einen Verstoß aus.

### Ziehe Batch-Verarbeitung in Betracht

Um Kosten in Situationen zu senken, in denen keine Echtzeit-Moderation erforderlich ist, ziehe in Betracht, Nachrichten in Batches zu moderieren. Nimm mehrere Nachrichten in den Kontext des Prompts auf und bitte Claude zu beurteilen, welche Nachrichten moderiert werden sollten.

<CodeGroup exclude="shell">
  ```python Python
  def batch_moderate_messages(messages, unsafe_categories):
      # Wandle die unsicheren Kategorien in einen String um, mit jeder Kategorie in einer neuen Zeile
      unsafe_category_str = "\n".join(unsafe_categories)

      # Formatiere den Nachrichten-String, wobei jede Nachricht in XML-ähnliche Tags eingeschlossen wird und eine ID erhält
      messages_str = "\n".join(
          [f"<message id={idx}>{msg}</message>" for idx, msg in enumerate(messages)]
      )

      # Erstelle den Prompt für Claude, einschließlich der Nachrichten und der unsicheren Kategorien
      assessment_prompt = f"""Determine the messages to moderate, based on the unsafe categories outlined below.

  Messages:
  <messages>
  {messages_str}
  </messages>

  Unsafe Categories:
  <categories>
  {unsafe_category_str}
  </categories>

  Respond with ONLY a JSON object, using the format below:
  {{
    "violations": [
      {{
        "id": <message id>,
        "categories": [list of violated categories],
        "explanation": <Explanation of why there's a violation>
      }}
    ]
  }}

  Important Notes:
  - Remember to analyze every message for a violation.
  - Select any number of violations that reasonably apply.
  - Do not include markdown formatting or code fences in your response."""

      # Sende die Anfrage zur Content-Moderation an Claude
      response = client.messages.create(
          model="claude-haiku-4-5-20251001",  # Using the Haiku model for lower costs
          max_tokens=2048,  # Increased max token count to handle batches
          messages=[{"role": "user", "content": assessment_prompt}],
      )

      # Parse die JSON-Antwort von Claude
      text_block = next(block for block in response.content if block.type == "text")
      assessment = json.loads(text_block.text)
      return assessment


  # Verarbeite den Batch von Kommentaren und hole die Antwort
  response_obj = batch_moderate_messages(user_comments, unsafe_categories)

  # Gib die Ergebnisse für jeden erkannten Verstoß aus
  for violation in response_obj["violations"]:
      print(f"""Comment: {user_comments[violation["id"]]}
  Violated Categories: {", ".join(violation["categories"])}
  Explanation: {violation["explanation"]}
  """)
  ```

  ```typescript TypeScript
  // Struktur der JSON-Batch-Bewertung, die Claude zurückgibt
  interface BatchAssessment {
    violations: {
      id: number;
      categories: string[];
      explanation: string;
    }[];
  }

  async function batchModerateMessages(
    messages: string[],
    unsafeCategories: string[]
  ): Promise<BatchAssessment> {
    // Wandle die unsicheren Kategorien in einen String um, mit jeder Kategorie in einer neuen Zeile
    const unsafeCategoryStr = unsafeCategories.join("\n");

    // Formatiere den Nachrichten-String, wobei jede Nachricht in XML-ähnliche Tags eingeschlossen ist und eine ID erhält
    const messagesStr = messages
      .map((msg, idx) => `<message id=${idx}>${msg}</message>`)
      .join("\n");

    // Erstelle den Prompt für Claude, einschließlich der Nachrichten und der unsicheren Kategorien
    const assessmentPrompt = `Determine the messages to moderate, based on the unsafe categories outlined below.

  Messages:
  <messages>
  ${messagesStr}
  </messages>

  Unsafe Categories:
  <categories>
  ${unsafeCategoryStr}
  </categories>

  Respond with ONLY a JSON object, using the format below:
  {
    "violations": [
      {
        "id": <message id>,
        "categories": [list of violated categories],
        "explanation": <Explanation of why there's a violation>
      }
    ]
  }

  Important Notes:
  - Remember to analyze every message for a violation.
  - Select any number of violations that reasonably apply.
  - Do not include markdown formatting or code fences in your response.`;

    // Sende die Anfrage zur Content-Moderation an Claude
    const response = await client.messages.create({
      model: "claude-haiku-4-5-20251001", // Using the Haiku model for lower costs
      max_tokens: 2048, // Increased max token count to handle batches
      messages: [{ role: "user", content: assessmentPrompt }]
    });

    // Parse die JSON-Antwort von Claude
    const textBlock = response.content.find((block) => block.type === "text");
    if (!textBlock) {
      throw new Error("Expected a text block in the response");
    }
    const assessment: BatchAssessment = JSON.parse(textBlock.text);
    return assessment;
  }

  // Verarbeite den Batch von Kommentaren und hole die Antwort
  const batchAssessment = await batchModerateMessages(userComments, unsafeCategories);

  // Gib die Ergebnisse für jeden erkannten Verstoß aus
  for (const violation of batchAssessment.violations) {
    console.log(`Comment: ${userComments[violation.id]}
  Violated Categories: ${violation.categories.join(", ")}
  Explanation: ${violation.explanation}
  `);
  }
  ```

  ```csharp C#
  async Task<JsonNode> BatchModerateMessages(IReadOnlyList<string> messages, IReadOnlyList<string> categories)
  {
      // Wandle die unsicheren Kategorien in einen String um, mit jeder Kategorie in einer neuen Zeile
      var unsafeCategoryText = string.Join("\n", categories);

      // Formatiere den Nachrichten-String, wobei jede Nachricht in XML-ähnliche Tags eingeschlossen wird und eine ID erhält
      var messagesText = string.Join(
          "\n",
          messages.Select((message, index) => $"<message id={index}>{message}</message>")
      );

      // Erstelle den Prompt für Claude, einschließlich der Nachrichten und der unsicheren Kategorien
      var assessmentPrompt = $$"""
  Determine the messages to moderate, based on the unsafe categories outlined below.

  Messages:
  <messages>
  {{messagesText}}
  </messages>

  Unsafe Categories:
  <categories>
  {{unsafeCategoryText}}
  </categories>

  Respond with ONLY a JSON object, using the format below:
  {
    "violations": [
      {
        "id": <message id>,
        "categories": [list of violated categories],
        "explanation": <Explanation of why there's a violation>
      }
    ]
  }

  Important Notes:
  - Remember to analyze every message for a violation.
  - Select any number of violations that reasonably apply.
  - Do not include markdown formatting or code fences in your response.
  """;

      // Sende die Anfrage zur Content-Moderation an Claude
      var response = await client.Messages.Create(
          new()
          {
              Model = Model.ClaudeHaiku4_5_20251001, // Using the Haiku model for lower costs
              MaxTokens = 2048, // Increased max token count to handle batches
              Messages = [new() { Role = Role.User, Content = assessmentPrompt }],
          }
      );

      // Grenze den ersten Content-Block auf einen Textblock ein und parse dann Claudes JSON-Antwort
      if (!response.Content[0].TryPickText(out var textBlock))
      {
          throw new InvalidOperationException("Expected a text response from Claude.");
      }
      return JsonNode.Parse(textBlock.Text)!;
  }

  // Verarbeite den Batch von Kommentaren und hole die Antwort
  var moderationResults = await BatchModerateMessages(userComments, unsafeCategories);

  // Gib die Ergebnisse für jeden erkannten Verstoß aus
  foreach (var violation in moderationResults["violations"]!.AsArray())
  {
      var flaggedComment = userComments[violation!["id"]!.GetValue<int>()];
      var violatedCategories = string.Join(
          ", ",
          violation["categories"]!.AsArray().Select(category => category!.GetValue<string>())
      );
      var explanation = violation["explanation"]!.GetValue<string>();

      Console.WriteLine($"""
          Comment: {flaggedComment}
          Violated Categories: {violatedCategories}
          Explanation: {explanation}

          """);
  }
  ```

  ```go Go
  // batchViolation ist ein Eintrag in Claudes "violations"-Array: der Index der
  // betreffenden Nachricht plus die verletzten Kategorien und die Begründung.
  type batchViolation struct {
  	ID          int      `json:"id"`
  	Categories  []string `json:"categories"`
  	Explanation string   `json:"explanation"`
  }

  func batchModerateMessages(messages []string, unsafeCategories []string) []batchViolation {
  	// Wandle die unsicheren Kategorien in einen String um, mit jeder Kategorie in einer neuen Zeile
  	unsafeCategoryStr := strings.Join(unsafeCategories, "\n")

  	// Formatiere den Nachrichten-String, wobei jede Nachricht in XML-ähnliche Tags eingeschlossen und mit einer ID versehen wird
  	messageLines := make([]string, len(messages))
  	for i, message := range messages {
  		messageLines[i] = fmt.Sprintf("<message id=%d>%s</message>", i, message)
  	}
  	messagesStr := strings.Join(messageLines, "\n")

  	// Erstelle den Prompt für Claude, einschließlich der Nachrichten und der unsicheren Kategorien
  	assessmentPrompt := fmt.Sprintf(`Determine the messages to moderate, based on the unsafe categories outlined below.

  Messages:
  <messages>
  %s
  </messages>

  Unsafe Categories:
  <categories>
  %s
  </categories>

  Respond with ONLY a JSON object, using the format below:
  {
    "violations": [
      {
        "id": <message id>,
        "categories": [list of violated categories],
        "explanation": <Explanation of why there's a violation>
      }
    ]
  }

  Important Notes:
  - Remember to analyze every message for a violation.
  - Select any number of violations that reasonably apply.
  - Do not include markdown formatting or code fences in your response.`, messagesStr, unsafeCategoryStr)

  	// Sende die Anfrage zur Content-Moderation an Claude
  	response, err := client.Messages.New(context.Background(), anthropic.MessageNewParams{
  		Model:     anthropic.ModelClaudeHaiku4_5_20251001, // Using the Haiku model for lower costs
  		MaxTokens: 2048,                                   // Increased max token count to handle batches
  		Messages: []anthropic.MessageParam{
  			anthropic.NewUserMessage(anthropic.NewTextBlock(assessmentPrompt)),
  		},
  	})
  	if err != nil {
  		log.Fatal(err)
  	}

  	// Grenze den ersten Content-Block auf einen Textblock ein, bevor du dessen Text liest
  	textBlock, ok := response.Content[0].AsAny().(anthropic.TextBlock)
  	if !ok {
  		log.Fatalf("expected a text block, got %q", response.Content[0].Type)
  	}

  	// Parse die JSON-Antwort von Claude
  	var assessment struct {
  		Violations []batchViolation `json:"violations"`
  	}
  	if err := json.Unmarshal([]byte(textBlock.Text), &assessment); err != nil {
  		log.Fatal(err)
  	}
  	return assessment.Violations
  }

  // moderateAllCommentsAsBatch moderiert den gesamten Batch von Kommentaren in einer
  // einzigen Anfrage und gibt die Ergebnisse für jeden erkannten Verstoß aus.
  func moderateAllCommentsAsBatch() {
  	// Verarbeite den Batch von Kommentaren und hole die Antwort
  	violations := batchModerateMessages(userComments, unsafeCategories)

  	// Gib die Ergebnisse für jeden erkannten Verstoß aus
  	for _, violation := range violations {
  		fmt.Printf(`Comment: %s
  Violated Categories: %s
  Explanation: %s

  `, userComments[violation.ID], strings.Join(violation.Categories, ", "), violation.Explanation)
  	}
  }
  ```

  ```java Java
  JsonNode batchModerateMessages(List<String> messages, List<String> unsafeCategories)
          throws JsonProcessingException {
      // Wandle die unsicheren Kategorien in einen String um, mit jeder Kategorie in einer neuen Zeile
      String unsafeCategoryStr = String.join("\n", unsafeCategories);

      // Formatiere den Nachrichten-String, wobei jede Nachricht in XML-ähnliche Tags eingeschlossen wird und eine ID erhält
      String messagesStr = IntStream.range(0, messages.size())
              .mapToObj(idx -> "<message id=%d>%s</message>".formatted(idx, messages.get(idx)))
              .collect(Collectors.joining("\n"));

      // Erstelle den Prompt für Claude, einschließlich der Nachrichten und der unsicheren Kategorien
      String assessmentPrompt = """
          Determine the messages to moderate, based on the unsafe categories outlined below.

          Messages:
          <messages>
          %s
          </messages>

          Unsafe Categories:
          <categories>
          %s
          </categories>

          Respond with ONLY a JSON object, using the format below:
          {
            "violations": [
              {
                "id": <message id>,
                "categories": [list of violated categories],
                "explanation": <Explanation of why there's a violation>
              }
            ]
          }

          Important Notes:
          - Remember to analyze every message for a violation.
          - Select any number of violations that reasonably apply.
          - Do not include markdown formatting or code fences in your response."""
              .formatted(messagesStr, unsafeCategoryStr);

      // Sende die Anfrage zur Content-Moderation an Claude
      Message response = client.messages().create(MessageCreateParams.builder()
              .model(Model.CLAUDE_HAIKU_4_5_20251001) // Using the Haiku model for lower costs
              .maxTokens(2048) // Increased max token count to handle batches
              .addUserMessage(assessmentPrompt)
              .build());

      // Parse die JSON-Antwort von Claude
      String assessmentJson = response.content().stream()
              .flatMap(contentBlock -> contentBlock.text().stream())
              .findFirst()
              .orElseThrow()
              .text();
      return new ObjectMapper().readTree(assessmentJson);
  }

  // Verarbeite den Batch von Kommentaren und gib die Ergebnisse für jeden erkannten Verstoß aus
  void printBatchViolations() throws JsonProcessingException {
      JsonNode response = batchModerateMessages(userComments, unsafeCategories);

      ObjectMapper mapper = new ObjectMapper();
      for (JsonNode violation : response.required("violations")) {
          List<String> violatedCategories =
                  mapper.convertValue(violation.required("categories"), new TypeReference<List<String>>() {});
          IO.println("""
                  Comment: %s
                  Violated Categories: %s
                  Explanation: %s
                  """.formatted(
                          userComments.get(violation.required("id").asInt()),
                          String.join(", ", violatedCategories),
                          violation.required("explanation").asText()));
      }
  }
  ```

  ```php PHP
  $batchModerateMessages = function (array $messages, array $unsafeCategories) use ($client): array {
      // Wandle die unsicheren Kategorien in einen String um, mit jeder Kategorie in einer neuen Zeile
      $unsafeCategoryStr = implode("\n", $unsafeCategories);

      // Formatiere den Nachrichten-String, wobei jede Nachricht in XML-ähnliche Tags eingeschlossen wird und eine ID erhält
      $messageLines = [];
      foreach ($messages as $idx => $msg) {
          $messageLines[] = "<message id={$idx}>{$msg}</message>";
      }
      $messagesStr = implode("\n", $messageLines);

      // Erstelle den Prompt für Claude, einschließlich der Nachrichten und der unsicheren Kategorien
      $assessmentPrompt = <<<PROMPT
      Determine the messages to moderate, based on the unsafe categories outlined below.

      Messages:
      <messages>
      {$messagesStr}
      </messages>

      Unsafe Categories:
      <categories>
      {$unsafeCategoryStr}
      </categories>

      Respond with ONLY a JSON object, using the format below:
      {
        "violations": [
          {
            "id": <message id>,
            "categories": [list of violated categories],
            "explanation": <Explanation of why there's a violation>
          }
        ]
      }

      Important Notes:
      - Remember to analyze every message for a violation.
      - Select any number of violations that reasonably apply.
      - Do not include markdown formatting or code fences in your response.
      PROMPT;

      // Sende die Anfrage zur Content-Moderation an Claude
      $response = $client->messages->create(
          model: 'claude-haiku-4-5-20251001', // Using the Haiku model for lower costs
          maxTokens: 2048, // Increased max token count to handle batches
          messages: [['role' => 'user', 'content' => $assessmentPrompt]],
      );

      // Parse die JSON-Antwort von Claude. Das SDK dekodiert jeden Content-Block
      // in seine konkrete Klasse, finde also den TextBlock, bevor du den Text liest.
      $textBlock = array_find($response->content, fn ($block) => $block instanceof \Anthropic\Messages\TextBlock)
          ?? throw new \RuntimeException('Expected a text block in the response.');

      return json_decode($textBlock->text, associative: true, flags: JSON_THROW_ON_ERROR);
  };

  // Verarbeite den Batch von Kommentaren und hole die Antwort
  $responseObj = $batchModerateMessages($userComments, $unsafeCategories);

  // Gib die Ergebnisse für jeden erkannten Verstoß aus
  foreach ($responseObj['violations'] as $violation) {
      echo "Comment: {$userComments[$violation['id']]}\n";
      echo 'Violated Categories: ' . implode(', ', $violation['categories']) . "\n";
      echo "Explanation: {$violation['explanation']}\n\n";
  }
  ```

  ```ruby Ruby
  def batch_moderate_messages(messages, unsafe_categories)
    # Wandle die unsicheren Kategorien in einen String um, mit jeder Kategorie in einer neuen Zeile
    unsafe_category_str = unsafe_categories.join("\n")

    # Formatiere den Nachrichten-String, wobei jede Nachricht in XML-ähnliche Tags eingeschlossen wird und eine ID erhält
    messages_str = messages
      .map.with_index { |message, index| "<message id=#{index}>#{message}</message>" }
      .join("\n")

    # Erstelle den Prompt für Claude, einschließlich der Nachrichten und der unsicheren Kategorien
    assessment_prompt = <<~PROMPT.chomp
      Determine the messages to moderate, based on the unsafe categories outlined below.

      Messages:
      <messages>
      #{messages_str}
      </messages>

      Unsafe Categories:
      <categories>
      #{unsafe_category_str}
      </categories>

      Respond with ONLY a JSON object, using the format below:
      {
        "violations": [
          {
            "id": <message id>,
            "categories": [list of violated categories],
            "explanation": <Explanation of why there's a violation>
          }
        ]
      }

      Important Notes:
      - Remember to analyze every message for a violation.
      - Select any number of violations that reasonably apply.
      - Do not include markdown formatting or code fences in your response.
    PROMPT

    # Sende die Anfrage zur Content-Moderation an Claude
    response = CLIENT.messages.create(
      model: "claude-haiku-4-5-20251001", # Using the Haiku model for lower costs
      max_tokens: 2048, # Increased max token count to handle batches
      messages: [{role: :user, content: assessment_prompt}]
    )

    # Parse die JSON-Antwort von Claude
    text_block = response.content.find { it.type == :text }
    JSON.parse(text_block.text)
  end


  # Verarbeite den Batch von Kommentaren und hole die Antwort
  response_obj = batch_moderate_messages(USER_COMMENTS, UNSAFE_CATEGORIES)

  # Gib die Ergebnisse für jeden erkannten Verstoß aus
  response_obj["violations"].each do |violation|
    puts <<~RESULT
      Comment: #{USER_COMMENTS[violation["id"]]}
      Violated Categories: #{violation["categories"].join(", ")}
      Explanation: #{violation["explanation"]}

    RESULT
  end
  ```
</CodeGroup>

In diesem Beispiel übernimmt die Funktion `batch_moderate_messages` die Moderation eines gesamten Batches von Nachrichten mit einem einzigen Claude-API-Aufruf. Innerhalb der Funktion wird ein Prompt erstellt, der die Liste der zu bewertenden Nachrichten und die unsicheren Inhaltskategorien enthält. Der Prompt weist Claude an, ein JSON-Objekt zurückzugeben, das alle Nachrichten auflistet, die Verstöße enthalten. Jede Nachricht in der Antwort wird durch ihre `id` identifiziert, die der Position der Nachricht im Batch entspricht. Bedenke, dass das Finden der optimalen Batch-Größe für deine spezifischen Bedürfnisse etwas Experimentieren erfordern kann. Größere Batch-Größen können zwar die Kosten senken, aber auch zu einer leichten Qualitätsminderung führen. Außerdem musst du möglicherweise den Parameter `max_tokens` im Claude-API-Aufruf erhöhen, um längere Antworten zu ermöglichen. Details zur maximalen Anzahl an Token, die dein gewähltes Modell ausgeben kann, findest du in der [Modellvergleichstabelle](https://platform.claude.com/docs/de/models/overview#latest-models-comparison).

<CardGroup cols={2}>
  <Card title="Cookbook zur Inhaltsmoderation" icon="link" href="https://platform.claude.com/cookbook/misc-building-moderation-filter">
    Sieh dir ein vollständig implementiertes, codebasiertes Beispiel an, wie du Claude für die Inhaltsmoderation verwenden kannst.
  </Card>

  <Card title="Jailbreaks abschwächen" icon="link" href="https://platform.claude.com/docs/de/test-and-evaluate/strengthen-guardrails/mitigate-jailbreaks">
    Erkunde Guardrail-Techniken zur Moderation von Interaktionen mit Claude.
  </Card>
</CardGroup>
