---
title: Moderazione dei contenuti
url: https://platform.claude.com/docs/it/about-claude/use-case-guides/content-moderation
description: La moderazione dei contenuti è un aspetto fondamentale per mantenere un ambiente sicuro, rispettoso e produttivo nelle applicazioni digitali. Questa guida illustra come Claude può essere utilizzato per moderare i contenuti all'interno della tua applicazione digitale.
---

> Visita il [cookbook sulla moderazione dei contenuti](https://platform.claude.com/cookbook/misc-building-moderation-filter) per vedere un esempio di implementazione della moderazione dei contenuti con Claude.

<Tip>
  Questa guida si concentra sulla moderazione dei contenuti generati dagli utenti all'interno della tua applicazione. Se cerchi indicazioni sulla moderazione delle interazioni con Claude, consulta 

  [Mitigare jailbreak e prompt injection](https://platform.claude.com/docs/it/test-and-evaluate/strengthen-guardrails/mitigate-jailbreaks)

  .
</Tip>

## Prima di sviluppare con Claude

### Decidi se usare Claude per la moderazione dei contenuti

Ecco alcuni indicatori chiave che suggeriscono di usare un "large language model" (grande modello linguistico), o LLM, come Claude invece di un approccio tradizionale basato su ML o su regole per la moderazione dei contenuti:

<AccordionGroup>
  <Accordion title="Desideri un'implementazione rapida ed economica">
    I metodi ML tradizionali richiedono notevoli risorse ingegneristiche, competenze di ML e costi di infrastruttura. I sistemi di moderazione umana comportano costi ancora più elevati. Con Claude, puoi avere un sistema di moderazione sofisticato operativo in molto meno tempo e a un costo molto inferiore.
  </Accordion>

  <Accordion title="Desideri sia comprensione semantica sia decisioni rapide">
    Gli approcci ML tradizionali, come i modelli bag-of-words o il semplice pattern matching, spesso faticano a comprendere il tono, l'intento e il contesto dei contenuti. Sebbene i sistemi di moderazione umana eccellano nella comprensione del significato semantico, richiedono tempo per la revisione dei contenuti. Claude risponde a entrambe le esigenze combinando la comprensione semantica con la capacità di fornire decisioni di moderazione rapidamente.
  </Accordion>

  <Accordion title="Hai bisogno di decisioni coerenti sulle policy">
    Sfruttando le sue avanzate capacità di ragionamento, Claude può interpretare e applicare linee guida di moderazione complesse in modo uniforme. Questa coerenza contribuisce a garantire un trattamento equo di tutti i contenuti, riducendo il rischio di decisioni di moderazione incoerenti o distorte che possono minare la fiducia degli utenti.
  </Accordion>

  <Accordion title="È probabile che le tue policy di moderazione cambino o si evolvano nel tempo">
    Una volta stabilito un approccio ML tradizionale, modificarlo è un'impresa laboriosa e che richiede molti dati. Al contrario, man mano che il tuo prodotto o le esigenze dei clienti si evolvono, Claude può adattarsi facilmente a modifiche o aggiunte alle policy di moderazione senza un'estesa rietichettatura dei dati di addestramento.
  </Accordion>

  <Accordion title="Richiedi un ragionamento interpretabile per le tue decisioni di moderazione">
    Se desideri fornire agli utenti o alle autorità di regolamentazione spiegazioni chiare alla base delle decisioni di moderazione, Claude può generare giustificazioni dettagliate e coerenti. Questa trasparenza è importante per costruire fiducia e garantire responsabilità nelle pratiche di moderazione dei contenuti.
  </Accordion>

  <Accordion title="Hai bisogno di supporto multilingue senza mantenere modelli separati">
    Gli approcci ML tradizionali richiedono in genere modelli separati o estesi processi di traduzione per ogni lingua supportata. La moderazione umana richiede l'assunzione di personale che parli fluentemente ogni lingua supportata. Le capacità multilingue di Claude gli consentono di classificare ticket in varie lingue senza la necessità di modelli separati o estesi processi di traduzione, semplificando la moderazione per basi di clienti globali.
  </Accordion>

  <Accordion title="Richiedi supporto multimodale">
    Le capacità multimodali di Claude gli consentono di analizzare e interpretare contenuti sia testuali sia visivi. Questo lo rende uno strumento versatile per una moderazione completa dei contenuti in ambienti in cui diversi tipi di media devono essere valutati insieme.
  </Accordion>
</AccordionGroup>

<Note>
  Tutti i modelli Claude sono addestrati con comportamenti di sicurezza integrati. Ciò può comportare che Claude moderi contenuti ritenuti particolarmente pericolosi (in linea con la 

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

  ), indipendentemente dal prompt utilizzato. Ad esempio, un sito web per adulti che desidera consentire agli utenti di pubblicare contenuti sessuali espliciti potrebbe riscontrare che Claude segnala comunque i contenuti espliciti come da moderare, anche se nel prompt viene specificato di non moderare i contenuti sessuali espliciti. Valuta di esaminare la AUP prima di sviluppare una soluzione di moderazione.
</Note>

### Genera esempi di contenuti da moderare

Prima di sviluppare una soluzione di moderazione dei contenuti, crea innanzitutto esempi di contenuti che dovrebbero essere segnalati e di contenuti che non dovrebbero esserlo. Assicurati di includere casi limite e scenari impegnativi che potrebbero essere difficili da gestire efficacemente per un sistema di moderazione dei contenuti. Successivamente, esamina i tuoi esempi per creare un elenco ben definito di categorie di moderazione. Ad esempio, gli esempi generati da una piattaforma di social media potrebbero includere quanto segue:

<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!",
  ]

  # Commenti utente di esempio per testare la moderazione dei contenuti
  user_comments = allowed_user_comments + disallowed_user_comments

  # Categorie considerate non sicure per la moderazione dei contenuti
  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!"
  ];

  // Commenti utente di esempio per testare la moderazione dei contenuti
  const userComments = [...allowedUserComments, ...disallowedUserComments];

  // Categorie considerate non sicure per la moderazione dei contenuti
  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!",
  ];

  // Commenti utente di esempio per testare la moderazione dei contenuti
  string[] userComments = [.. allowedUserComments, .. disallowedUserComments];

  // Categorie considerate non sicure per la moderazione dei contenuti
  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!",
  }

  // Commenti utente di esempio per testare la moderazione dei contenuti
  var userComments = slices.Concat(allowedUserComments, disallowedUserComments)

  // Categorie considerate non sicure per la moderazione dei contenuti
  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!");

  // Commenti utente di esempio per testare la moderazione dei contenuti
  final List<String> userComments =
          Stream.concat(allowedUserComments.stream(), disallowedUserComments.stream()).toList();

  // Categorie considerate non sicure per la moderazione dei contenuti
  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!',
  ];

  // Commenti utente di esempio per testare la moderazione dei contenuti
  $userComments = [...$allowedUserComments, ...$disallowedUserComments];

  // Categorie considerate non sicure per la moderazione dei contenuti
  $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!"
  ]

  # Commenti utente di esempio per testare la moderazione dei contenuti
  USER_COMMENTS = ALLOWED_USER_COMMENTS + DISALLOWED_USER_COMMENTS

  # Categorie considerate non sicure per la moderazione dei contenuti
  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>

Moderare efficacemente questi esempi richiede una comprensione sfumata del linguaggio. Nel commento `This movie was great, I really enjoyed it. The main actor really killed it!`, il sistema di moderazione dei contenuti deve riconoscere che "killed it" è una metafora, non un'indicazione di violenza reale. Al contrario, nonostante l'assenza di menzioni esplicite di violenza, il commento `Delete this post now or you better hide. I am coming after you and your family.` dovrebbe essere segnalato dal sistema di moderazione dei contenuti.

Le categorie non sicure possono essere personalizzate per adattarsi alle tue esigenze specifiche. Ad esempio, se desideri impedire ai minori di creare contenuti sul tuo sito web, potresti aggiungere "Underage Posting" alle categorie.

***

## Come moderare i contenuti usando Claude

### Seleziona il modello Claude giusto

Quando selezioni un modello, è importante considerare la dimensione dei tuoi dati. Se i costi sono un problema, un modello più piccolo come Claude Haiku 5.5 è una scelta eccellente grazie al suo rapporto costo-efficacia. Di seguito è riportata una stima del costo per moderare il testo di una piattaforma di social media che riceve un miliardo di post al mese:

* **Dimensione dei contenuti**

  * Post al mese: 1 mld
  * Caratteri per post: 100
  * Caratteri totali: 100 mld

* **Token stimati**

  * Token di input: 28,6 mld (ipotizzando 1 token ogni 3,5 caratteri)
  * Percentuale di messaggi segnalati: 3%
  * Token di output per messaggio segnalato: 50
  * Token di output totali: 1,5 mld

* **Costo stimato di Claude Haiku 5.5**

  * Costo dei token di input: 28.600 MTok \* $0,10/MTok = $2.860 USD
  * Costo dei token di output: 1.500 MTok \* $0,50/MTok = $750 USD
  * Costo mensile: $2.860 + $750 = $3.610 USD

* **Costo stimato di Claude Opus 5**

  * Costo dei token di input: 28.600 MTok \* $5,00/MTok = $143.000 USD
  * Costo dei token di output: 1.500 MTok \* $25,00/MTok = $37.500 USD
  * Costo mensile: $143.000 + $37.500 = $180.500 USD

* **Costo stimato di Claude Opus 4.8**

  * Costo dei token di input: 28.600 MTok \* $5,00/MTok = $143.000 USD
  * Costo dei token di output: 1.500 MTok \* $25,00/MTok = $37.500 USD
  * Costo mensile: $143.000 + $37.500 = $180.500 USD

<Tip>
  I costi effettivi possono differire da queste stime. Queste stime si basano sul prompt evidenziato nella sezione sull'

  [elaborazione in batch](https://platform.claude.com/docs/it/about-claude/use-case-guides/content-moderation#consider-batch-processing)

  . I token di output possono essere ulteriormente ridotti rimuovendo il campo 

  `explanation`

   dalla risposta.
</Tip>

### Costruisci un prompt solido

Per usare Claude per la moderazione dei contenuti, Claude deve comprendere i requisiti di moderazione della tua applicazione. Inizia scrivendo un prompt che ti consenta di definire le tue esigenze di moderazione:

<CodeGroup exclude="shell">
  ```python Python
  def moderate_message(message, unsafe_categories):
      # Converti le categorie non sicure in una stringa, con ogni categoria su una nuova riga
      unsafe_category_str = "\n".join(unsafe_categories)

      # Costruisci il prompt per Claude, includendo il messaggio e le categorie non sicure
      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."""

      # Invia la richiesta a Claude per la moderazione dei contenuti
      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}],
      )

      # Analizza la risposta JSON di Claude
      text_block = next(block for block in response.content if block.type == "text")
      assessment = json.loads(text_block.text)

      # Estrai lo stato di violazione dalla valutazione
      contains_violation = assessment["violation"]

      # Se c'è una violazione, ottieni le categorie e la spiegazione; altrimenti usa valori predefiniti vuoti
      violated_categories = assessment.get("categories", []) if contains_violation else []
      explanation = assessment.get("explanation") if contains_violation else None

      return contains_violation, violated_categories, explanation


  # Elabora ogni commento e stampa i risultati
  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
  // Struttura della valutazione JSON restituita da Claude
  interface ModerationAssessment {
    violation: boolean;
    categories?: string[];
    explanation?: string;
  }

  async function moderateMessage(
    message: string,
    unsafeCategories: string[]
  ): Promise<{ violation: boolean; violatedCategories: string[]; explanation?: string }> {
    // Converti le categorie non sicure in una stringa, con ogni categoria su una nuova riga
    const unsafeCategoryStr = unsafeCategories.join("\n");

    // Costruisci il prompt per Claude, includendo il messaggio e le categorie non sicure
    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.`;

    // Invia la richiesta a Claude per la moderazione dei contenuti
    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 }]
    });

    // Analizza la risposta JSON di 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);

    // Estrai lo stato di violazione dalla valutazione
    const containsViolation = assessment.violation;

    // Se c'è una violazione, ottieni le categorie e la spiegazione; altrimenti usa valori predefiniti vuoti
    const violatedCategories = containsViolation ? (assessment.categories ?? []) : [];
    const explanation = containsViolation ? assessment.explanation : undefined;

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

  // Elabora ogni commento e stampa i risultati
  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
  )
  {
      // Converti le categorie non sicure in una stringa, con ogni categoria su una nuova riga
      var unsafeCategoryText = string.Join("\n", categories);

      // Costruisci il prompt per Claude, includendo il messaggio e le categorie non sicure
      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.
  """;

      // Invia la richiesta a Claude per la moderazione dei contenuti
      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 }],
          }
      );

      // Restringi il primo blocco di contenuto a un blocco di testo, poi analizza la risposta JSON di Claude
      if (!response.Content[0].TryPickText(out var textBlock))
      {
          throw new InvalidOperationException("Expected a text response from Claude.");
      }
      var assessment = JsonNode.Parse(textBlock.Text)!;

      // Estrai lo stato di violazione dalla valutazione
      var containsViolation = assessment["violation"]!.GetValue<bool>();

      // Se c'è una violazione, ottieni le categorie e la spiegazione; altrimenti usa valori predefiniti vuoti
      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);
  }

  // Elabora ogni commento e stampa i risultati
  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) {
  	// Converti le categorie non sicure in una stringa, con ogni categoria su una nuova riga
  	unsafeCategoryStr := strings.Join(unsafeCategories, "\n")

  	// Costruisci il prompt per Claude, includendo il messaggio e le categorie non sicure
  	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)

  	// Invia la richiesta a Claude per la moderazione dei contenuti
  	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)
  	}

  	// Restringi il primo blocco di contenuto a un blocco di testo prima di leggerne il testo
  	textBlock, ok := response.Content[0].AsAny().(anthropic.TextBlock)
  	if !ok {
  		log.Fatalf("expected a text block, got %q", response.Content[0].Type)
  	}

  	// Analizza la risposta JSON di 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)
  	}

  	// Se c'è una violazione, restituisci le categorie e la spiegazione; altrimenti usa valori predefiniti vuoti
  	if !assessment.Violation {
  		return false, nil, ""
  	}
  	return true, assessment.Categories, assessment.Explanation
  }

  // moderateAllComments elabora ogni commento e stampa i risultati.
  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 {
      // Converti le categorie non sicure in una stringa, con ogni categoria su una nuova riga
      String unsafeCategoryStr = String.join("\n", unsafeCategories);

      // Costruisci il prompt per Claude, includendo il messaggio e le categorie non sicure
      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);

      // Invia la richiesta a Claude per la moderazione dei contenuti
      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());

      // Analizza la risposta JSON di Claude
      String assessmentJson = response.content().stream()
              .flatMap(contentBlock -> contentBlock.text().stream())
              .findFirst()
              .orElseThrow()
              .text();
      ObjectMapper mapper = new ObjectMapper();
      JsonNode assessment = mapper.readTree(assessmentJson);

      // Estrai lo stato di violazione dalla valutazione
      boolean containsViolation = assessment.required("violation").asBoolean();

      // Se c'è una violazione, ottieni le categorie e la spiegazione; altrimenti usa valori predefiniti vuoti
      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);
  }

  // Elabora ogni commento e stampa i risultati
  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 {
      // Converti le categorie non sicure in una stringa, con ogni categoria su una nuova riga
      $unsafeCategoryStr = implode("\n", $unsafeCategories);

      // Costruisci il prompt per Claude, includendo il messaggio e le categorie non sicure
      $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;

      // Invia la richiesta a Claude per la moderazione dei contenuti
      $response = $client->messages->create(
          model: 'claude-haiku-4-5-20251001', // Using the Haiku model for lower costs
          maxTokens: 200,
          messages: [['role' => 'user', 'content' => $assessmentPrompt]],
      );

      // Analizza la risposta JSON di Claude. L'SDK decodifica ogni blocco di contenuto
      // nella sua classe concreta, quindi trova il TextBlock prima di leggere il testo.
      $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);

      // Estrai lo stato di violazione dalla valutazione
      $containsViolation = $assessment['violation'];

      // Se c'è una violazione, ottieni le categorie e la spiegazione; altrimenti usa valori predefiniti vuoti
      $violatedCategories = $containsViolation ? ($assessment['categories'] ?? []) : [];
      $explanation = $containsViolation ? ($assessment['explanation'] ?? null) : null;

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

  // Elabora ogni commento e stampa i risultati
  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)
    # Converti le categorie non sicure in una stringa, con ogni categoria su una nuova riga
    unsafe_category_str = unsafe_categories.join("\n")

    # Costruisci il prompt per Claude, includendo il messaggio e le categorie non sicure
    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

    # Invia la richiesta a Claude per la moderazione dei contenuti
    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}]
    )

    # Analizza la risposta JSON di Claude
    text_block = response.content.find { it.type == :text }
    assessment = JSON.parse(text_block.text)

    # Estrai lo stato di violazione dalla valutazione
    contains_violation = assessment["violation"]

    # Se c'è una violazione, ottieni le categorie e la spiegazione; altrimenti usa valori predefiniti vuoti
    violated_categories = contains_violation ? assessment.fetch("categories", []) : []
    explanation = contains_violation ? assessment["explanation"] : nil

    [contains_violation, violated_categories, explanation]
  end


  # Elabora ogni commento e stampa i risultati
  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 questo esempio, la funzione `moderate_message` contiene un prompt di valutazione che include le categorie di contenuti non sicuri e il messaggio da valutare. Il prompt chiede a Claude di valutare se il messaggio debba essere moderato, in base alle categorie non sicure definite in precedenza.

La valutazione del modello viene quindi analizzata per determinare se vi sia una violazione. In caso di violazione, Claude restituisce anche un elenco delle categorie violate e una spiegazione del motivo per cui il messaggio non è sicuro.

### Valuta il tuo prompt

La moderazione dei contenuti è un problema di classificazione. Pertanto, puoi usare le stesse tecniche descritte nel [cookbook sulla classificazione](https://platform.claude.com/cookbook/capabilities-classification-guide) per determinare l'accuratezza del tuo sistema di moderazione dei contenuti.

Un'ulteriore considerazione è che, invece di trattare la moderazione dei contenuti come un problema di classificazione binaria, puoi creare più categorie per rappresentare vari livelli di rischio. Creare più livelli di rischio ti consente di regolare l'aggressività della moderazione. Ad esempio, potresti voler bloccare automaticamente le query degli utenti ritenute ad alto rischio, mentre gli utenti con molte query a rischio medio vengono segnalati per una revisione umana.

<CodeGroup exclude="shell">
  ```python Python
  def assess_risk_level(message, unsafe_categories):
      # Converti le categorie non sicure in una stringa, con ogni categoria su una nuova riga
      unsafe_category_str = "\n".join(unsafe_categories)

      # Costruisci il prompt per Claude, includendo il messaggio, le categorie non sicure e le definizioni dei livelli di rischio
      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."""

      # Invia la richiesta a Claude per la valutazione del rischio
      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}],
      )

      # Analizza la risposta JSON di Claude
      text_block = next(block for block in response.content if block.type == "text")
      assessment = json.loads(text_block.text)

      # Estrai il livello di rischio, le categorie violate e la spiegazione dalla valutazione
      risk_level = assessment["risk_level"]
      violated_categories = assessment["categories"]
      explanation = assessment.get("explanation")

      return risk_level, violated_categories, explanation


  # Elabora ogni commento e stampa i risultati
  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
  // Struttura della valutazione del rischio JSON restituita da Claude
  interface RiskAssessment {
    risk_level: number;
    categories: string[];
    explanation?: string;
  }

  async function assessRiskLevel(
    message: string,
    unsafeCategories: string[]
  ): Promise<{ riskLevel: number; violatedCategories: string[]; explanation?: string }> {
    // Converti le categorie non sicure in una stringa, con ogni categoria su una nuova riga
    const unsafeCategoryStr = unsafeCategories.join("\n");

    // Costruisci il prompt per Claude, includendo il messaggio, le categorie non sicure e le definizioni dei livelli di rischio
    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.`;

    // Invia la richiesta a Claude per la valutazione del rischio
    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 }]
    });

    // Analizza la risposta JSON di 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);

    // Estrai dalla valutazione il livello di rischio, le categorie violate e la spiegazione
    const { risk_level: riskLevel, categories: violatedCategories, explanation } = assessment;

    return { riskLevel, violatedCategories, explanation };
  }

  // Elabora ogni commento e stampa i risultati
  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
  )
  {
      // Converti le categorie non sicure in una stringa, con ogni categoria su una nuova riga
      var unsafeCategoryText = string.Join("\n", categories);

      // Costruisci il prompt per Claude, includendo il messaggio, le categorie non sicure e le definizioni dei livelli di rischio
      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.
  """;

      // Invia la richiesta a Claude per la valutazione del rischio
      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 }],
          }
      );

      // Restringi il primo blocco di contenuto a un blocco di testo, poi analizza la risposta JSON di Claude
      if (!response.Content[0].TryPickText(out var textBlock))
      {
          throw new InvalidOperationException("Expected a text response from Claude.");
      }
      var assessment = JsonNode.Parse(textBlock.Text)!;

      // Estrai il livello di rischio, le categorie violate e la spiegazione dalla valutazione
      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);
  }

  // Elabora ogni commento e stampa i risultati
  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) {
  	// Converti le categorie non sicure in una stringa, con ogni categoria su una nuova riga
  	unsafeCategoryStr := strings.Join(unsafeCategories, "\n")

  	// Costruisci il prompt per Claude, includendo il messaggio, le categorie non sicure e le definizioni dei livelli di rischio
  	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)

  	// Invia la richiesta a Claude per la valutazione del rischio
  	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)
  	}

  	// Restringi il primo blocco di contenuto a un blocco di testo prima di leggerne il testo
  	textBlock, ok := response.Content[0].AsAny().(anthropic.TextBlock)
  	if !ok {
  		log.Fatalf("expected a text block, got %q", response.Content[0].Type)
  	}

  	// Analizza la risposta JSON di 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)
  	}

  	// Restituisci il livello di rischio, le categorie violate e la spiegazione dalla valutazione
  	return assessment.RiskLevel, assessment.Categories, assessment.Explanation
  }

  // assessAllRiskLevels elabora ogni commento e stampa i risultati.
  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 {
      // Converti le categorie non sicure in una stringa, con ogni categoria su una nuova riga
      String unsafeCategoryStr = String.join("\n", unsafeCategories);

      // Costruisci il prompt per Claude, includendo il messaggio, le categorie non sicure e le definizioni dei livelli di rischio
      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);

      // Invia la richiesta a Claude per la valutazione del rischio
      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());

      // Analizza la risposta JSON di Claude
      String assessmentJson = response.content().stream()
              .flatMap(contentBlock -> contentBlock.text().stream())
              .findFirst()
              .orElseThrow()
              .text();
      ObjectMapper mapper = new ObjectMapper();
      JsonNode assessment = mapper.readTree(assessmentJson);

      // Estrai il livello di rischio, le categorie violate e la spiegazione dalla valutazione
      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);
  }

  // Elabora ogni commento e stampa i risultati
  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 {
      // Converti le categorie non sicure in una stringa, con ogni categoria su una nuova riga
      $unsafeCategoryStr = implode("\n", $unsafeCategories);

      // Costruisci il prompt per Claude, includendo il messaggio, le categorie non sicure e le definizioni dei livelli di rischio
      $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;

      // Invia la richiesta a Claude per la valutazione del rischio
      $response = $client->messages->create(
          model: 'claude-haiku-4-5-20251001', // Using the Haiku model for lower costs
          maxTokens: 200,
          messages: [['role' => 'user', 'content' => $assessmentPrompt]],
      );

      // Analizza la risposta JSON di Claude. L'SDK decodifica ogni blocco di contenuto
      // nella sua classe concreta, quindi trova il TextBlock prima di leggere il testo.
      $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);

      // Estrai il livello di rischio, le categorie violate e la spiegazione dalla valutazione
      $riskLevel = $assessment['risk_level'];
      $violatedCategories = $assessment['categories'];
      $explanation = $assessment['explanation'] ?? null;

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

  // Elabora ogni commento e stampa i risultati
  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)
    # Converti le categorie non sicure in una stringa, con ogni categoria su una nuova riga
    unsafe_category_str = unsafe_categories.join("\n")

    # Costruisci il prompt per Claude, includendo il messaggio, le categorie non sicure e le definizioni dei livelli di rischio
    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

    # Invia la richiesta a Claude per la valutazione del rischio
    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}]
    )

    # Analizza la risposta JSON di Claude
    text_block = response.content.find { it.type == :text }
    assessment = JSON.parse(text_block.text)

    # Estrai il livello di rischio, le categorie violate e la spiegazione dalla valutazione
    risk_level = assessment["risk_level"]
    violated_categories = assessment["categories"]
    explanation = assessment["explanation"]

    [risk_level, violated_categories, explanation]
  end


  # Elabora ogni commento e stampa i risultati
  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>

Questo codice implementa una funzione `assess_risk_level` che usa Claude per valutare il livello di rischio di un messaggio. La funzione accetta come input un messaggio e le categorie non sicure.

All'interno della funzione viene generato un prompt per Claude, che include il messaggio da valutare, le categorie non sicure e istruzioni specifiche per la valutazione del livello di rischio. Il prompt istruisce Claude a rispondere con un oggetto JSON che include il livello di rischio, le categorie violate e una spiegazione facoltativa.

Questo approccio consente una moderazione dei contenuti flessibile tramite l'assegnazione di livelli di rischio. Può essere integrato senza difficoltà in un sistema più ampio per automatizzare il filtraggio dei contenuti o segnalare commenti per la revisione umana in base al livello di rischio valutato. Ad esempio, eseguendo questo codice, il commento `Delete this post now or you better hide. I am coming after you and your family.` viene identificato come ad alto rischio a causa della sua pericolosa minaccia. Al contrario, il commento `Stay away from the 5G cellphones!! They are using 5G to control you.` viene classificato come a rischio medio.

### Distribuisci il tuo prompt

Una volta che sei sicuro della qualità della tua soluzione, è il momento di distribuirla in produzione. Ecco alcune best practice da seguire quando usi la moderazione dei contenuti in produzione:

1. **Fornisci un feedback chiaro agli utenti:** quando l'input di un utente viene bloccato o una risposta viene segnalata a causa della moderazione dei contenuti, fornisci un feedback informativo e costruttivo per aiutare gli utenti a capire perché il loro messaggio è stato segnalato e come possono riformularlo in modo appropriato. Negli esempi di codice precedenti, ciò avviene tramite il campo `explanation` nella risposta di Claude.

2. **Analizza i contenuti moderati:** tieni traccia dei tipi di contenuti segnalati dal tuo sistema di moderazione per identificare tendenze e potenziali aree di miglioramento.

3. **Valuta e migliora continuamente:** valuta regolarmente le prestazioni del tuo sistema di moderazione dei contenuti usando metriche come il monitoraggio di precision e recall. Usa questi dati per perfezionare in modo iterativo i tuoi prompt di moderazione, le parole chiave e i criteri di valutazione.

***

## Migliora le prestazioni

In scenari complessi, può essere utile considerare strategie aggiuntive per migliorare le prestazioni oltre alle [tecniche di prompt engineering](https://platform.claude.com/docs/it/build-with-claude/prompt-engineering/overview) standard. Ecco alcune strategie avanzate:

### Definisci gli argomenti e fornisci esempi

Oltre a elencare le categorie non sicure nel prompt, è possibile ottenere ulteriori miglioramenti fornendo definizioni e frasi relative a ciascuna categoria.

<CodeGroup exclude="shell">
  ```python Python
  # Categorie considerate non sicure per la moderazione dei contenuti, con le relative definizioni
  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):
      # Formatta la stringa delle categorie non sicure, con ogni categoria e la sua definizione su una nuova riga
      unsafe_category_str = "\n".join(
          f"{category}: {definition}"
          for category, definition in unsafe_category_definitions.items()
      )

      # Costruisci il prompt per Claude, includendo il messaggio e le categorie non sicure
      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."""

      # Invia la richiesta a Claude per la moderazione dei contenuti
      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}],
      )

      # Analizza la risposta JSON di Claude
      text_block = next(block for block in response.content if block.type == "text")
      assessment = json.loads(text_block.text)

      # Estrai lo stato di violazione dalla valutazione
      contains_violation = assessment["violation"]

      # Se c'è una violazione, ottieni le categorie e la spiegazione; altrimenti usa valori predefiniti vuoti
      violated_categories = assessment.get("categories", []) if contains_violation else []
      explanation = assessment.get("explanation") if contains_violation else None

      return contains_violation, violated_categories, explanation


  # Elabora ogni commento e stampa i risultati
  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
  // Struttura della valutazione JSON restituita da Claude
  interface DefinitionBasedAssessment {
    violation: boolean;
    categories?: string[];
    explanation?: string;
  }

  // Categorie considerate non sicure per la moderazione dei contenuti, con le relative definizioni
  // (le chiavi dell'oggetto mantengono l'ordine di inserimento, quindi le categorie appaiono in questo ordine)
  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 }> {
    // Formatta la stringa delle categorie non sicure, con ogni categoria e la sua definizione su una nuova riga
    const unsafeCategoryStr = Object.entries(unsafeCategoryDefinitions)
      .map(([category, definition]) => `${category}: ${definition}`)
      .join("\n");

    // Costruisci il prompt per Claude, includendo il messaggio e le categorie non sicure
    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.`;

    // Invia la richiesta a Claude per la moderazione dei contenuti
    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 }]
    });

    // Analizza la risposta JSON di 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);

    // Estrai lo stato di violazione dalla valutazione
    const containsViolation = assessment.violation;

    // Se c'è una violazione, ottieni le categorie e la spiegazione; altrimenti usa valori predefiniti vuoti
    const violatedCategories = containsViolation ? (assessment.categories ?? []) : [];
    const explanation = containsViolation ? assessment.explanation : undefined;

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

  // Elabora ogni commento e stampa i risultati
  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#
  // Categorie considerate non sicure per la moderazione dei contenuti, con le loro definizioni.
  // Le voci restano nell'ordine di inserimento, quindi il prompt generato elenca le categorie
  // esattamente in questo ordine.
  (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
  )
  {
      // Formatta la stringa delle categorie non sicure, con ogni categoria e la sua definizione su una nuova riga
      var unsafeCategoryText = string.Join(
          "\n",
          categoryDefinitions.Select(entry => $"{entry.Category}: {entry.Definition}")
      );

      // Costruisci il prompt per Claude, includendo il messaggio e le categorie non sicure
      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.
  """;

      // Invia la richiesta a Claude per la moderazione dei contenuti
      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 }],
          }
      );

      // Restringi il primo blocco di contenuto a un blocco di testo, poi analizza la risposta JSON di Claude
      if (!response.Content[0].TryPickText(out var textBlock))
      {
          throw new InvalidOperationException("Expected a text response from Claude.");
      }
      var assessment = JsonNode.Parse(textBlock.Text)!;

      // Estrai lo stato di violazione dalla valutazione
      var containsViolation = assessment["violation"]!.GetValue<bool>();

      // Se c'è una violazione, ottieni le categorie e la spiegazione; altrimenti usa valori predefiniti vuoti
      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);
  }

  // Elabora ogni commento e stampa i risultati
  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
  // Categorie considerate non sicure per la moderazione dei contenuti, con le relative definizioni.
  // Uno slice di coppie categoria/definizione (anziché una map) mantiene stabile l'ordine
  // di rendering; le map di Go vengono iterate in ordine casuale.
  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) {
  	// Formatta la stringa delle categorie non sicure, con ogni categoria e la sua definizione su una nuova riga
  	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")

  	// Costruisci il prompt per Claude, includendo il messaggio e le categorie non sicure
  	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)

  	// Invia la richiesta a Claude per la moderazione dei contenuti
  	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)
  	}

  	// Restringi il primo blocco di contenuto a un blocco di testo prima di leggerne il testo
  	textBlock, ok := response.Content[0].AsAny().(anthropic.TextBlock)
  	if !ok {
  		log.Fatalf("expected a text block, got %q", response.Content[0].Type)
  	}

  	// Analizza la risposta JSON di 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)
  	}

  	// Se c'è una violazione, restituisci le categorie e la spiegazione; altrimenti usa valori predefiniti vuoti
  	if !assessment.Violation {
  		return false, nil, ""
  	}
  	return true, assessment.Categories, assessment.Explanation
  }

  // moderateAllCommentsWithDefinitions elabora ogni commento e stampa i risultati.
  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
  // Categorie considerate non sicure per la moderazione dei contenuti, con le relative definizioni
  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 {
      // Formatta la stringa delle categorie non sicure, con ogni categoria e la sua definizione su una nuova riga
      String unsafeCategoryStr = unsafeCategoryDefinitions.stream()
              .map(categoryDefinition ->
                      categoryDefinition.category() + ": " + categoryDefinition.definition())
              .collect(Collectors.joining("\n"));

      // Costruisci il prompt per Claude, includendo il messaggio e le categorie non sicure
      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);

      // Invia la richiesta a Claude per la moderazione dei contenuti
      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());

      // Analizza la risposta JSON di Claude
      String assessmentJson = response.content().stream()
              .flatMap(contentBlock -> contentBlock.text().stream())
              .findFirst()
              .orElseThrow()
              .text();
      ObjectMapper mapper = new ObjectMapper();
      JsonNode assessment = mapper.readTree(assessmentJson);

      // Estrai lo stato di violazione dalla valutazione
      boolean containsViolation = assessment.required("violation").asBoolean();

      // Se c'è una violazione, ottieni le categorie e la spiegazione; altrimenti usa valori predefiniti vuoti
      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);
  }

  // Elabora ogni commento e stampa i risultati
  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
  // Categorie considerate non sicure per la moderazione dei contenuti, con le relative definizioni
  $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 {
      // Formatta la stringa delle categorie non sicure, con ogni categoria e la sua definizione su una nuova riga
      $categoryLines = [];
      foreach ($unsafeCategoryDefinitions as $category => $definition) {
          $categoryLines[] = "{$category}: {$definition}";
      }
      $unsafeCategoryStr = implode("\n", $categoryLines);

      // Costruisci il prompt per Claude, includendo il messaggio e le categorie non sicure
      $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;

      // Invia la richiesta a Claude per la moderazione dei contenuti
      $response = $client->messages->create(
          model: 'claude-haiku-4-5-20251001', // Using the Haiku model for lower costs
          maxTokens: 200,
          messages: [['role' => 'user', 'content' => $assessmentPrompt]],
      );

      // Analizza la risposta JSON di Claude. L'SDK decodifica ogni blocco di contenuto
      // nella sua classe concreta, quindi trova il TextBlock prima di leggere il testo.
      $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);

      // Estrai lo stato di violazione dalla valutazione
      $containsViolation = $assessment['violation'];

      // Se c'è una violazione, ottieni le categorie e la spiegazione; altrimenti usa valori predefiniti vuoti
      $violatedCategories = $containsViolation ? ($assessment['categories'] ?? []) : [];
      $explanation = $containsViolation ? ($assessment['explanation'] ?? null) : null;

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

  // Elabora ogni commento e stampa i risultati
  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
  # Categorie considerate non sicure per la moderazione dei contenuti, con le relative definizioni
  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)
    # Formatta la stringa delle categorie non sicure, con ogni categoria e la sua definizione su una nuova riga
    unsafe_category_str = unsafe_category_definitions
      .map { |category, definition| "#{category}: #{definition}" }
      .join("\n")

    # Costruisci il prompt per Claude, includendo il messaggio e le categorie non sicure
    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

    # Invia la richiesta a Claude per la moderazione dei contenuti
    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}]
    )

    # Analizza la risposta JSON di Claude
    text_block = response.content.find { it.type == :text }
    assessment = JSON.parse(text_block.text)

    # Estrai lo stato di violazione dalla valutazione
    contains_violation = assessment["violation"]

    # Se c'è una violazione, ottieni le categorie e la spiegazione; altrimenti usa valori predefiniti vuoti
    violated_categories = contains_violation ? assessment.fetch("categories", []) : []
    explanation = contains_violation ? assessment["explanation"] : nil

    [contains_violation, violated_categories, explanation]
  end


  # Elabora ogni commento e stampa i risultati
  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>

La funzione `moderate_message_with_definitions` estende la precedente funzione `moderate_message` consentendo di associare a ciascuna categoria non sicura una definizione dettagliata. Nel codice ciò avviene sostituendo la raccolta `unsafe_categories` della funzione originale con una mappatura `unsafe_category_definitions`. Questa mappatura associa ciascuna categoria non sicura alla definizione corrispondente. Sia i nomi delle categorie sia le loro definizioni sono inclusi nel prompt.

In particolare, la definizione della categoria `Specialized Advice` ora specifica i tipi di consulenza finanziaria che dovrebbero essere vietati. Di conseguenza, il commento `It is a great time to invest in gold!`, che in precedenza superava la valutazione di `moderate_message`, ora genera una violazione.

### Considera l'elaborazione in batch

Per ridurre i costi in situazioni in cui la moderazione in tempo reale non è necessaria, considera di moderare i messaggi in batch. Includi più messaggi nel contesto del prompt e chiedi a Claude di valutare quali messaggi debbano essere moderati.

<CodeGroup exclude="shell">
  ```python Python
  def batch_moderate_messages(messages, unsafe_categories):
      # Converti le categorie non sicure in una stringa, con ogni categoria su una nuova riga
      unsafe_category_str = "\n".join(unsafe_categories)

      # Formatta la stringa dei messaggi, con ogni messaggio racchiuso in tag simil-XML e dotato di un ID
      messages_str = "\n".join(
          [f"<message id={idx}>{msg}</message>" for idx, msg in enumerate(messages)]
      )

      # Costruisci il prompt per Claude, includendo i messaggi e le categorie non sicure
      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."""

      # Invia la richiesta a Claude per la moderazione dei contenuti
      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}],
      )

      # Analizza la risposta JSON di Claude
      text_block = next(block for block in response.content if block.type == "text")
      assessment = json.loads(text_block.text)
      return assessment


  # Elabora il batch di commenti e ottieni la risposta
  response_obj = batch_moderate_messages(user_comments, unsafe_categories)

  # Stampa i risultati per ogni violazione rilevata
  for violation in response_obj["violations"]:
      print(f"""Comment: {user_comments[violation["id"]]}
  Violated Categories: {", ".join(violation["categories"])}
  Explanation: {violation["explanation"]}
  """)
  ```

  ```typescript TypeScript
  // Struttura della valutazione batch JSON restituita da Claude
  interface BatchAssessment {
    violations: {
      id: number;
      categories: string[];
      explanation: string;
    }[];
  }

  async function batchModerateMessages(
    messages: string[],
    unsafeCategories: string[]
  ): Promise<BatchAssessment> {
    // Converti le categorie non sicure in una stringa, con ogni categoria su una nuova riga
    const unsafeCategoryStr = unsafeCategories.join("\n");

    // Formatta la stringa dei messaggi, con ogni messaggio racchiuso in tag simil-XML e dotato di un ID
    const messagesStr = messages
      .map((msg, idx) => `<message id=${idx}>${msg}</message>`)
      .join("\n");

    // Costruisci il prompt per Claude, includendo i messaggi e le categorie non sicure
    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.`;

    // Invia la richiesta a Claude per la moderazione dei contenuti
    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 }]
    });

    // Analizza la risposta JSON di 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;
  }

  // Elabora il batch di commenti e ottieni la risposta
  const batchAssessment = await batchModerateMessages(userComments, unsafeCategories);

  // Stampa i risultati per ogni violazione rilevata
  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)
  {
      // Converti le categorie non sicure in una stringa, con ogni categoria su una nuova riga
      var unsafeCategoryText = string.Join("\n", categories);

      // Formatta la stringa dei messaggi, con ogni messaggio racchiuso in tag simil-XML e dotato di un ID
      var messagesText = string.Join(
          "\n",
          messages.Select((message, index) => $"<message id={index}>{message}</message>")
      );

      // Costruisci il prompt per Claude, includendo i messaggi e le categorie non sicure
      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.
  """;

      // Invia la richiesta a Claude per la moderazione dei contenuti
      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 }],
          }
      );

      // Restringi il primo blocco di contenuto a un blocco di testo, poi analizza la risposta JSON di Claude
      if (!response.Content[0].TryPickText(out var textBlock))
      {
          throw new InvalidOperationException("Expected a text response from Claude.");
      }
      return JsonNode.Parse(textBlock.Text)!;
  }

  // Elabora il batch di commenti e ottieni la risposta
  var moderationResults = await BatchModerateMessages(userComments, unsafeCategories);

  // Stampa i risultati per ogni violazione rilevata
  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 è una voce dell'array "violations" di Claude: l'indice del
  // messaggio incriminato più le categorie violate e il motivo.
  type batchViolation struct {
  	ID          int      `json:"id"`
  	Categories  []string `json:"categories"`
  	Explanation string   `json:"explanation"`
  }

  func batchModerateMessages(messages []string, unsafeCategories []string) []batchViolation {
  	// Converti le categorie non sicure in una stringa, con ogni categoria su una nuova riga
  	unsafeCategoryStr := strings.Join(unsafeCategories, "\n")

  	// Formatta la stringa dei messaggi, con ogni messaggio racchiuso in tag simil-XML e dotato di un ID
  	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")

  	// Costruisci il prompt per Claude, includendo i messaggi e le categorie non sicure
  	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)

  	// Invia la richiesta a Claude per la moderazione dei contenuti
  	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)
  	}

  	// Restringi il primo blocco di contenuto a un blocco di testo prima di leggerne il testo
  	textBlock, ok := response.Content[0].AsAny().(anthropic.TextBlock)
  	if !ok {
  		log.Fatalf("expected a text block, got %q", response.Content[0].Type)
  	}

  	// Analizza la risposta JSON di 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 modera l'intero batch di commenti in una singola
  // richiesta e stampa i risultati per ogni violazione rilevata.
  func moderateAllCommentsAsBatch() {
  	// Elabora il batch di commenti e ottieni la risposta
  	violations := batchModerateMessages(userComments, unsafeCategories)

  	// Stampa i risultati per ogni violazione rilevata
  	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 {
      // Converti le categorie non sicure in una stringa, con ogni categoria su una nuova riga
      String unsafeCategoryStr = String.join("\n", unsafeCategories);

      // Formatta la stringa dei messaggi, con ogni messaggio racchiuso in tag simil-XML e dotato di un ID
      String messagesStr = IntStream.range(0, messages.size())
              .mapToObj(idx -> "<message id=%d>%s</message>".formatted(idx, messages.get(idx)))
              .collect(Collectors.joining("\n"));

      // Costruisci il prompt per Claude, includendo i messaggi e le categorie non sicure
      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);

      // Invia la richiesta a Claude per la moderazione dei contenuti
      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());

      // Analizza la risposta JSON di Claude
      String assessmentJson = response.content().stream()
              .flatMap(contentBlock -> contentBlock.text().stream())
              .findFirst()
              .orElseThrow()
              .text();
      return new ObjectMapper().readTree(assessmentJson);
  }

  // Elabora il batch di commenti e stampa i risultati per ogni violazione rilevata
  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 {
      // Converti le categorie non sicure in una stringa, con ogni categoria su una nuova riga
      $unsafeCategoryStr = implode("\n", $unsafeCategories);

      // Formatta la stringa dei messaggi, con ogni messaggio racchiuso in tag simil-XML e dotato di un ID
      $messageLines = [];
      foreach ($messages as $idx => $msg) {
          $messageLines[] = "<message id={$idx}>{$msg}</message>";
      }
      $messagesStr = implode("\n", $messageLines);

      // Costruisci il prompt per Claude, includendo i messaggi e le categorie non sicure
      $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;

      // Invia la richiesta a Claude per la moderazione dei contenuti
      $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]],
      );

      // Analizza la risposta JSON di Claude. L'SDK decodifica ogni blocco di contenuto
      // nella sua classe concreta, quindi trova il TextBlock prima di leggere il testo.
      $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);
  };

  // Elabora il batch di commenti e ottieni la risposta
  $responseObj = $batchModerateMessages($userComments, $unsafeCategories);

  // Stampa i risultati per ogni violazione rilevata
  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)
    # Converti le categorie non sicure in una stringa, con ogni categoria su una nuova riga
    unsafe_category_str = unsafe_categories.join("\n")

    # Formatta la stringa dei messaggi, con ogni messaggio racchiuso in tag simil-XML e dotato di un ID
    messages_str = messages
      .map.with_index { |message, index| "<message id=#{index}>#{message}</message>" }
      .join("\n")

    # Costruisci il prompt per Claude, includendo i messaggi e le categorie non sicure
    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

    # Invia la richiesta a Claude per la moderazione dei contenuti
    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}]
    )

    # Analizza la risposta JSON di Claude
    text_block = response.content.find { it.type == :text }
    JSON.parse(text_block.text)
  end


  # Elabora il batch di commenti e ottieni la risposta
  response_obj = batch_moderate_messages(USER_COMMENTS, UNSAFE_CATEGORIES)

  # Stampa i risultati per ogni violazione rilevata
  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 questo esempio, la funzione `batch_moderate_messages` gestisce la moderazione di un intero batch di messaggi con una singola chiamata all'API di Claude. All'interno della funzione viene creato un prompt che include l'elenco dei messaggi da valutare e le categorie di contenuti non sicuri. Il prompt indica a Claude di restituire un oggetto JSON che elenca tutti i messaggi contenenti violazioni. Ogni messaggio nella risposta è identificato dal suo `id`, che corrisponde alla posizione del messaggio nel batch. Tieni presente che trovare la dimensione ottimale del batch per le tue esigenze specifiche potrebbe richiedere qualche sperimentazione. Sebbene batch di dimensioni maggiori possano ridurre i costi, potrebbero anche comportare una leggera diminuzione della qualità. Inoltre, potrebbe essere necessario aumentare il parametro `max_tokens` nella chiamata all'API di Claude per gestire risposte più lunghe. Per i dettagli sul numero massimo di token che il modello scelto può produrre in output, consulta la [tabella di confronto dei modelli](https://platform.claude.com/docs/it/models/overview#latest-models-comparison).

<CardGroup cols={2}>
  <Card title="Cookbook sulla moderazione dei contenuti" icon="link" href="https://platform.claude.com/cookbook/misc-building-moderation-filter">
    Visualizza un esempio di codice completamente implementato su come usare Claude per la moderazione dei contenuti.
  </Card>

  <Card title="Mitigare i jailbreak" icon="link" href="https://platform.claude.com/docs/it/test-and-evaluate/strengthen-guardrails/mitigate-jailbreaks">
    Esplora le tecniche di guardrail per moderare le interazioni con Claude.
  </Card>
</CardGroup>
