> ## Documentation Index
> Fetch the complete documentation index at: https://www.ayrshare.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# 內容審核

> 檢查內容以確保沒有有害或不當內容

export const HeaderAPI = ({noProfileKey, profileKeyRequired}) => <>
    <ParamField header="Authorization" type="string" required>
      <a href="/apis/overview#authorization">API Key</a> of the Primary Profile.
      <br />
      <br />
      Format: <code>Authorization: Bearer API_KEY</code>
    </ParamField>
    {!noProfileKey && (profileKeyRequired ? <ParamField header="Profile-Key" type="string" required>
          <a href="/apis/overview#profile-key-format">Profile Key</a> of a User Profile.
          <br />
          <br />
          Format: <code>Profile-Key: PROFILE_KEY</code>
        </ParamField> : <ParamField header="Profile-Key" type="string">
          <a href="/apis/overview#profile-key-format">Profile Key</a> of a User Profile.
          <br />
          <br />
          Format: <code>Profile-Key: PROFILE_KEY</code>
        </ParamField>)}
  </>;

export const PlansAvailable = ({plans = [], maxPackRequired}) => {
  let displayPlans = plans;
  if (plans && plans.length === 1) {
    const lowerCasePlan = plans[0].toLowerCase();
    if (lowerCasePlan === "business") {
      displayPlans = ["Launch", "Business", "Enterprise"];
    } else if (lowerCasePlan === "premium") {
      displayPlans = ["Premium", "Launch", "Business", "Enterprise"];
    }
  }
  return <Note>
Available on {displayPlans.length === 1 ? "the " : ""}
{displayPlans.join(", ").replace(/\b\w/g, l => l.toUpperCase())}{" "}
{displayPlans.length > 1 ? "plans" : "plan"}.

{maxPackRequired && <span onClick={() => window.open('https://www.ayrshare.com/docs/additional/maxpack', '_self')} className="flex items-center mt-2 cursor-pointer">
 <span className="px-1.5 py-0.5 rounded text-sm" style={{
    backgroundColor: '#C264B6',
    color: 'white',
    fontSize: '12px'
  }}>
   Max Pack required
 </span>
</span>}
</Note>;
};

<PlansAvailable plans={["premium"]} maxPackRequired={false} />

內容審核 API 旨在協助開發者辨識可能有害或不當的文字內容。
此端點會分析你輸入的文字，並依據多種類型的問題內容進行分類。

## 主要特色

<ul className="custom-bullets">
  <li>自動偵測有害內容。</li>
  <li>多種類別的問題文字。</li>
  <li>可輕鬆整合以進行內容過濾。</li>
</ul>

## 運作方式

當你將文字傳送至此審核端點時，它會透過 OpenAI 模型分析內容。API 接著會回傳結果，指出該文字是否屬於已定義的問題類別。

## 有害內容類別

此 API 會將文字分類為以下類別：

| 類別                     | 說明                                                                                  |
| ---------------------- | ----------------------------------------------------------------------------------- |
| hate                   | 基於種族、性別、族裔、宗教、國籍、性向、身心障礙狀態或種姓，表達、煽動或宣揚仇恨的內容。針對非受保護群體（例如西洋棋玩家）的仇恨內容屬於騷擾（harassment）。 |
| hate/threatening       | 仇恨內容且同時包含基於種族、性別、族裔、宗教、國籍、性向、身心障礙狀態或種姓對目標群體的暴力或嚴重傷害。                                |
| harassment             | 對任何對象表達、煽動或宣揚騷擾語言的內容。                                                               |
| harassment/threatening | 騷擾內容且同時包含對任何對象的暴力或嚴重傷害。                                                             |
| self-harm              | 宣揚、鼓勵或描繪自我傷害行為（例如自殺、自殘與飲食失調）的內容。                                                    |
| self-harm/intent       | 敘述者表達自己正在進行或打算進行自我傷害行為（例如自殺、自殘與飲食失調）的內容。                                            |
| self-harm/instructions | 鼓勵進行自我傷害行為（例如自殺、自殘與飲食失調）的內容，或提供如何進行此類行為的指示或建議。                                      |
| sexual                 | 意圖引發性興奮的內容，例如描述性行為，或宣傳性服務（不含性教育與健康養護）。                                              |
| sexual/minors          | 包含未滿 18 歲個體的性內容。                                                                    |
| violence               | 描繪死亡、暴力或身體傷害的內容。                                                                    |
| violence/graphic       | 以圖像化細節描繪死亡、暴力或身體傷害的內容。                                                              |

## 使用方式與最佳實務

1. **最佳文字長度**：為求最佳結果，我們建議將長文字切分為較小的區段。建議每段少於 2,000 字元。
2. **整合方式**：使用此 API 自動標記你的應用程式、論壇或使用者產生內容平台上可能有問題的內容。
3. **依結果採取行動**：根據 API 的輸出結果，你可以採取適當的行動，例如過濾內容、警示使用者，或進一步審查流程。

## 標頭參數

<HeaderAPI noProfileKey={true} />

## Body 參數

<ParamField body="text" type="string">
  要進行審核分析的文字。
</ParamField>

<ParamField body="imageUrl" type="string">
  圖片的 URL。必須以 `https://` 開頭。
</ParamField>

<RequestExample>
  ```bash cURL theme={"system"}
  curl --location 'https://api.ayrshare.com/api/validate/moderation' \
  --header 'Authorization: Bearer API_KEY' \
  --header 'Content-Type: application/json' \
  --data '{
      "text": "Let'\''s kill '\''em all"
  }'
  ```

  ```javascript JavaScript theme={"system"}
  const url = "https://api.ayrshare.com/api/validate/moderation";
  const apiKey = "API_KEY"; // Replace with your actual API key

  const data = {
    text: "Let's kill 'em all",
  };

  fetch(url, {
    method: "POST",
    headers: {
      Authorization: `Bearer ${apiKey}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify(data),
  })
    .then((response) => response.json())
    .then((result) => console.log(result))
    .catch((error) => console.error("Error:", error));
  ```

  ```python Python theme={"system"}
  import requests

  url = 'https://api.ayrshare.com/api/validate/moderation'
  api_key = 'API_KEY'  # Replace with your actual API key

  headers = {
      'Authorization': f'Bearer {api_key}',
      'Content-Type': 'application/json'
  }

  data = {
      'text': "Let's kill 'em all"
  }

  response = requests.post(url, json=data, headers=headers)

  if response.status_code == 200:
      result = response.json()
      print(result)
  else:
      print(f"Error: {response.status_code}")
      print(response.text)
  ```

  ```php PHP theme={"system"}
  <?php

  $url = 'https://api.ayrshare.com/api/validate/moderation';
  $apiKey = 'API_KEY';  // Replace with your actual API key

  $data = [
      'text' => "Let's kill 'em all"
  ];

  $headers = [
      'Authorization: Bearer ' . $apiKey,
      'Content-Type: application/json'
  ];

  $ch = curl_init($url);

  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_POST, true);
  curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
  curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

  $response = curl_exec($ch);

  if (curl_errno($ch)) {
      echo 'Error: ' . curl_error($ch);
  } else {
      $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
      if ($httpCode == 200) {
          $result = json_decode($response, true);
          print_r($result);
      } else {
          echo "Error: HTTP Code " . $httpCode . "\n";
          echo $response;
      }
  }
  ```

  ```go Go theme={"system"}
  package main

  import (
  	"bytes"
  	"encoding/json"
  	"fmt"
  	"io/ioutil"
  	"net/http"
  )

  func main() {
  	url := "https://api.ayrshare.com/api/validate/moderation"
  	apiKey := "API_KEY" // Replace with your actual API key

  	// Create the request body
  	requestBody, err := json.Marshal(map[string]string{
  		"text": "Let's kill 'em all",
  	})
  	if err != nil {
  		fmt.Println("Error creating request body:", err)
  		return
  	}

  	// Create a new request
  	req, err := http.NewRequest("POST", url, bytes.NewBuffer(requestBody))
  	if err != nil {
  		fmt.Println("Error creating request:", err)
  		return
  	}

  	// Set headers
  	req.Header.Set("Authorization", "Bearer "+apiKey)
  	req.Header.Set("Content-Type", "application/json")

  	// Send the request
  	client := &http.Client{}
  	resp, err := client.Do(req)
  	if err != nil {
  		fmt.Println("Error sending request:", err)
  		return
  	}
  	defer resp.Body.Close()

  	// Read the response
  	body, err := ioutil.ReadAll(resp.Body)
  	if err != nil {
  		fmt.Println("Error reading response:", err)
  		return
  	}

  	// Check the status code
  	if resp.StatusCode == http.StatusOK {
  		fmt.Println("Response:")
  		fmt.Println(string(body))
  	} else {
  		fmt.Printf("Error: Status Code %d\n", resp.StatusCode)
  		fmt.Println(string(body))
  	}
  }
  ```

  ```csharp C# theme={"system"}
  using System;
  using System.Net.Http;
  using System.Text;
  using System.Threading.Tasks;
  using System.Text.Json;

  class Program
  {
      static async Task Main(string[] args)
      {
          string url = "https://api.ayrshare.com/api/validate/moderation";
          string apiKey = "API_KEY";  // Replace with your actual API key

          var data = new
          {
              text = "Let's kill 'em all"
          };

          using (var client = new HttpClient())
          {
              client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");

              var content = new StringContent(JsonSerializer.Serialize(data), Encoding.UTF8, "application/json");

              try
              {
                  HttpResponseMessage response = await client.PostAsync(url, content);

                  if (response.IsSuccessStatusCode)
                  {
                      string result = await response.Content.ReadAsStringAsync();
                      Console.WriteLine("Response:");
                      Console.WriteLine(result);
                  }
                  else
                  {
                      Console.WriteLine($"Error: {response.StatusCode}");
                      Console.WriteLine(await response.Content.ReadAsStringAsync());
                  }
              }
              catch (HttpRequestException e)
              {
                  Console.WriteLine($"Request error: {e.Message}");
                  Console.WriteLine($"InnerException: {e.InnerException?.Message}"); // Include inner exception details for more information
              }
          }
      }
  }
  ```
</RequestExample>

<ResponseExample>
  ```json 200: Response theme={"system"}
  {
    "status": "success",
    "text": "Let's kill 'em all",
    "moderation": [
      {
        "flagged": true,
        "categories": {
          "sexual": false,
          "hate": false,
          "harassment": false,
          "self-harm": false,
          "sexual/minors": false,
          "hate/threatening": false,
          "violence/graphic": false,
          "self-harm/intent": false,
          "self-harm/instructions": false,
          "harassment/threatening": false,
          "violence": true
        },
        "categoryScores": {
          "sexual": 0.00002128273445123341,
          "hate": 0.027735227718949318,
          "harassment": 0.08523011207580566,
          "self-harm": 0.0000021838018255948555,
          "sexual/minors": 1.924875903114298e-7,
          "hate/threatening": 0.0063302298076450825,
          "violence/graphic": 0.00024857991957105696,
          "self-harm/intent": 7.833968993509188e-7,
          "self-harm/instructions": 8.686130570367823e-8,
          "harassment/threatening": 0.07459623366594315,
          "violence": 0.9833663702011108
        }
      }
    ]
  }
  ```

  ```json 400: Bad Request theme={"system"}
  {
    "action": "generate",
    "status": "error",
    "code": 331,
    "message": "There was an issue with the AI processing. Please try again and if the issue persists, contact us."
  }
  ```
</ResponseExample>
