detoxify_sh

The Elixir client for the Detoxify API: toxicity scores for any text, from one call. Elixir 1.17 and later; it uses Req, which Phoenix applications usually have already. It works from Erlang and Gleam too.

# mix.exs
def deps do
  [
    {:detoxify_sh, "~> 0.1"}
  ]
end
client = DetoxifySh.new() # reads DETOXIFY_API_KEY

{:ok, result} = DetoxifySh.analyze(client, "You are a wonderful person")

if result.scores.toxicity > 0.8 do
  # hold the comment for review
end

result.scores is a %DetoxifySh.Scores{} with six probabilities from 0 to 1: toxicity, severe_toxicity, obscene, threat, insult and identity_attack. Your application chooses the thresholds. DetoxifySh.analyze!/2 returns the result and raises the error instead.

Calls are synchronous. To score text without holding up the caller, run them in a Task.

In a Phoenix application

Keep the key in config/runtime.exs, where every client finds it:

config :detoxify_sh, api_key: System.get_env("DETOXIFY_API_KEY")

A client is plain data, so make it where it is used:

defmodule MyApp.Moderation do
  def review(comment) do
    case DetoxifySh.analyze(DetoxifySh.new(), comment.body) do
      {:ok, %{scores: %{toxicity: toxicity}}} when toxicity > 0.8 -> :hold
      {:ok, _result} -> :publish
      {:error, %DetoxifySh.QuotaExceededError{help_url: url}} -> {:hold, "more at #{url}"}
      {:error, _error} -> :hold
    end
  end
end

To use your application's own connection pool, pass it to Req: DetoxifySh.new(req_options: [finch: MyApp.Finch]).

Configuration

DetoxifySh.new(
  api_key: "dtx_…", # default: config, then DETOXIFY_API_KEY; nil calls without a key
  base_url: "https://api.detoxify.sh", # the default
  timeout: 30_000, # milliseconds, per attempt
  max_retries: 2,
  cache: true # the default: the application's cache; false turns it off
)

Each option left out is read from config :detoxify_sh, <option>: … before its default, so config :detoxify_sh, base_url: "https://detoxify-proxy.example.com" points every client at another address, such as your own proxy.

Get an API key from the console. Without one, calls are anonymous and limited to a few a day. Keep the key on your server. Neither the client's inspected form nor any error shows it.

Errors

analyze/2 returns {:error, exception}, and analyze!/2 raises it. Every exception has:

Match on the exception to handle one kind of problem:

Exception When
DetoxifySh.InvalidRequestError The text is empty or too long (invalid_request, payload_too_large).
DetoxifySh.AuthenticationError The API key was not accepted.
DetoxifySh.QuotaExceededError The free plan's month, or the anonymous day, is used up. See help_url.
DetoxifySh.AccountSuspendedError Unpaid usage must be paid first. See help_url.
DetoxifySh.RateLimitError Too many requests in a short time.
DetoxifySh.ServiceUnavailableError The service could not answer right now.
DetoxifySh.NetworkError The API could not be reached, or did not answer in time.
DetoxifySh.Error Anything else, including codes newer than this client.
case DetoxifySh.analyze(client, text) do
  {:ok, result} -> result
  {:error, %DetoxifySh.QuotaExceededError{help_url: url}} -> IO.puts("More at #{url}")
  {:error, error} -> raise error
end

Retries

These are retried up to max_retries times:

The client waits as long as the API asks, up to 60 seconds, or else backs off exponentially from half a second. Quota, suspension, key and validation errors are not retried. Req's own retries are turned off, so a call is never retried twice over.

A call the API served, but whose answer was lost on the way back, is charged again when it is retried.

Caching

The client remembers recent results in memory, so analyzing the same text again returns at once, without calling the API or being charged. Up to 1,000 results are kept (the least recently used go first), each for six hours after it was fetched, however often it is read. Errors are never kept.

The results live in DetoxifySh.Cache, a process that owns an ETS table. The :detoxify_sh application starts one when your application starts, and every client shares it, so there is nothing to set up. Results are kept per API address, so a client of one address never answers from another address's results. Texts can be up to 10,000 characters, so at the default size the cache holds a few tens of megabytes at most.

To size the default cache, or turn it off:

config :detoxify_sh, cache: [max_size: 5_000, max_age: :timer.hours(1)]
config :detoxify_sh, cache: false # starts no cache; clients then keep nothing

To keep a cache of your own, start one under your supervisor and name it:

children = [
  {DetoxifySh.Cache, name: MyApp.DetoxifyCache, max_size: 5_000}
]

DetoxifySh.new(cache: MyApp.DetoxifyCache)

DetoxifySh.new(cache: false) keeps nothing for that client. max_size: 0 makes a cache that keeps nothing; max_age: :infinity keeps results until they are pushed out.