API reference
Everything the Slop Monkey API does, on one page. For a quick start, see the API page. The same contract, machine-readable: openapi.yaml.
Overview
The base address is https://slopmonkey.app/api/v1. Requests and responses are JSON in UTF-8. Only https is accepted: a request over plain http is refused with https_required.
| Endpoint | What it does |
|---|---|
POST /api/v1/rewrites | Rewrites text. Answers with JSON, or with server-sent events when "stream": true. |
GET /api/v1/usage | Your API word balance and this month’s use. Free. |
GET /api/v1/ping | Checks that the API is up and that a key works. Free. |
Every response has a Request-Id header: req_ and 22 letters and digits. A successful body carries the same value as id, and an error body as request_id. Quote it when you write to support. Responses carry Cache-Control: no-store.
Keys are made and managed on the keys page, never through the API itself, so a key that leaks can’t make more keys.
Authentication
Send your key in the Authorization header, after the word Bearer:
Authorization: Bearer sm_live_4f9QkZr2Wb7XcT1nLp0Ya3SdEu8VmHgJ1kQz9XNothing else works: not X-Api-Key, not a query string, not a cookie. When a key arrives the wrong way, the 401 message says what was wrong.
Keys
A key is sm_live_ or sm_test_, then 32 random letters and digits, then a 6-character checksum: 46 characters in all, matching ^sm_(live|test)_[0-9A-Za-z]{38}$. The checksum lets us tell a mistyped key from a wrong one. A key is shown once, when you create it. We keep only a one-way hash of it and its last 4 characters, so we can’t show it to you again.
sm_live_ | sm_test_ | |
|---|---|---|
| Who can make one | Any signed-in account, at once. Its requests spend API words, so buy some first. | Any signed-in account |
| Rewriter | The real model | A rough stand-in that swaps some words for synonyms, at once |
| Words | Charged from the API word balance | Nothing charged; the response shows what a live request would charge |
| Requests a minute | 60 for the account | 30 for the account |
| Forcing errors | No | Yes, with the Slopmonkey-Test header |
Getting live keys. On the keys page, sign in with Google and buy a pack of API words: it goes straight to Stripe’s checkout page, with nothing to fill in first. When you come back, the words are in your balance and a live key is ready, shown once. You can also make live keys yourself at any time. A live key with no words answers 402 insufficient_words until you buy some. Buying words or making a live key means you agree to the API terms and the acceptable-use policy. An account can hold 10 active keys.
Keeping keys safe. Keep a key on your server, in an environment variable. Never put it in a web page, an app people download, or a repository. The API refuses requests from browsers (browser_not_allowed) and sends no CORS headers, so a key in front-end code does not work.
Rotating a key. Create a second key, deploy it, then revoke the first. Revoking takes effect on the next request, and the revoked key gets revoked_api_key from then on.
Rewrite
POST /api/v1/rewrites rewrites a draft so it reads like a person wrote it. It answers when the rewrite is finished, or, with "stream": true, sends the rewrite as it is written (Streaming).
| Header | |
|---|---|
Authorization | Required. Bearer and your key. |
Content-Type | Required. application/json. |
Idempotency-Key | Optional and strongly recommended. 1 to 255 printable ASCII characters; a UUID is ideal. See Idempotency. |
Slopmonkey-Test | Test keys only. Forces an error or a scenario. See Test mode. |
Request body
| Field | Type | Default | Rules |
|---|---|---|---|
text | string | required | The draft: 1 to 5,000 words (how words are counted). Any Unicode except NUL and unpaired surrogates. \r\n is read as \n. Leading and trailing whitespace is dropped. |
protect | array of strings | [] | Up to 50 entries, each 1 to 400 characters. Each is kept exactly, character for character, wherever it occurs in text (case-sensitive). An entry that doesn’t occur gives a protect_not_found warning, not an error. |
protect_quotes | boolean | true | Also keep every quotation of 3 or more words (or 6 or more Chinese characters) in double quotation marks on one line, up to 400 characters. |
include | array of strings | [] | Extras in the response. In v1 the only value is "checks" (Checks). Any other value answers invalid_parameter. |
stream | boolean | false | Answer with server-sent events (Streaming). |
Any other field is refused with unknown_parameter, with a suggestion when it looks like a typo, so "protected" fails loudly instead of being ignored. The whole body may be at most 128 KB.
There is no strength, tone or language setting: the model has one setting, and it handles English and Chinese without being told. For a stronger rewrite, send the output back as the new text. That is what Go further does in the app, and it is charged again.
Example
curl https://slopmonkey.app/api/v1/rewrites \
-H "Authorization: Bearer $SLOPMONKEY_API_KEY" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: 6f1c2b7e-3f43-4c39-9a0e-0d8f6a1b2c3d" \
-d '{
"text": "In the ever-evolving landscape of remote work, it is important to note that clear communication plays a pivotal role in fostering collaboration. Acme Corp found that teams who wrote things down shipped 23% faster.",
"protect": ["Acme Corp"],
"include": ["checks"]
}'Response
{
"id": "req_5bT2wQ9mXc7KdLz0RfVa1p",
"object": "rewrite",
"created": 1767225600,
"livemode": true,
"replayed": false,
"output": "Remote work runs on clear communication. At Acme Corp, teams that wrote things down shipped 23% faster.",
"words_in": 34,
"words_out": 17,
"sections": 1,
"warnings": [],
"usage": { "words_charged": 100, "balance": 48212 },
"checks": {
"facts_checked": 2,
"facts_kept": 2,
"missing": [],
"added_numbers": []
}
}| Field | Meaning |
|---|---|
id | The request id, the same as the Request-Id header. A rewrite can’t be fetched again by its id in v1. |
object | Always "rewrite". |
created | When it was made, in Unix seconds. |
livemode | false for a test key. |
replayed | true when this answers a repeated Idempotency-Key: the text was rewritten again and nothing was charged (Idempotency). |
output | The rewrite. Sections are joined with the whitespace that separated them in text. Protected passages are exactly as sent. |
words_in, words_out | Words in text and in output. |
sections | How many pieces the text was cut into and rewritten separately. Usually 1 for text under about 370 words. The joins between sections are worth one read. |
warnings | Things worth a look, as { "code", "message", "section" }. Empty when there are none (Warnings). |
usage.words_charged | API words this request took. 0 on a replay. With a test key, what a live request would have charged, though nothing is taken. |
usage.balance | API words left in the account after this request. With a test key, the live balance, unchanged. |
checks | Only with "include": ["checks"] (Checks). |
New fields may be added within v1. Ignore any you don’t recognise.
Warnings
| Code | When | Charged? |
|---|---|---|
section_unchanged | After 3 tries, the rewrite of a section still changed a protected passage, so that section is returned exactly as sent. | No. That section’s words are free. |
section_truncated | A section reached the model’s length limit, and its end may be cut off. | Yes, since text was written. |
protect_not_found | A protect entry does not occur in text. Usually a typo. | Not applicable. |
section is the section’s number, counting from 0, or null when the warning is about the whole request. New warning codes may be added within v1.
Checks
With "include": ["checks"] the response has a checks object: the same fact check the app runs, over the whole text. It compares the numbers, ranges, links, quotations and names in your draft with the rewrite.
| Field | Meaning |
|---|---|
facts_checked | How many facts were found in the draft. |
facts_kept | How many of them are in the rewrite. |
missing | Facts not found in the rewrite, as { "kind", "value", "section" }. kind is number, range, link, quote or name. |
added_numbers | Numbers in the rewrite that were not in the draft. |
A missing item means “check this by hand”, not proof of a mistake: the model may have written a number out in words. Protected passages are left out of the check, because they are kept exactly.
Streaming
With "stream": true, the answer arrives as server-sent events while it is written. Auth, validation, balance, caps and rate limits are checked first, so those failures are ordinary JSON errors with their HTTP status. Once the server answers 200 with Content-Type: text/event-stream; charset=utf-8, everything else arrives as events.
Each event is a line event: <name>, a line data: <JSON on one line>, and a blank line. There are no id: or retry: lines: a stream can’t be resumed, so retry the request with the same Idempotency-Key instead.
| Event | Data | Notes |
|---|---|---|
rewrite.started | { id, object, livemode, words_in, sections, usage: { words_reserved, balance } } | First, at once. balance is after the words are held. |
text.delta | { section, text } | Add text to the end of section section. Sections arrive strictly in order. Joining every delta in order gives output. |
section.reset | { section, reason } | Throw away what you have for that section: it is being written again. reason is language or protected_text. Rare. |
section.done | { section, status } | status is rewritten, unchanged (the section was sent again exactly as written) or truncated. |
ping | {} | Every 15 seconds while nothing else is sent, so proxies keep the connection open. |
rewrite.completed | The whole response, exactly as the JSON answer | Last event when it works. The final usage is here. |
error | { error: { type, code, message, param, doc_url }, request_id } | Last event when it fails. Nothing is charged: the words are returned before this event is sent. |
New event types may be added within v1. Ignore any you don’t recognise. A stream that ends without rewrite.completed or error was cut off: retry with the same Idempotency-Key (how a cut-off request is charged).
event: rewrite.started
data: {"id":"req_5bT2wQ9mXc7KdLz0RfVa1p","object":"rewrite","livemode":true,"words_in":34,"sections":1,"usage":{"words_reserved":100,"balance":48212}}
event: text.delta
data: {"section":0,"text":"Remote work runs"}
event: text.delta
data: {"section":0,"text":" on clear communication."}
event: text.delta
data: {"section":0,"text":" At Acme Corp, teams that wrote things down shipped 23% faster."}
event: section.done
data: {"section":0,"status":"rewritten"}
event: rewrite.completed
data: {"id":"req_5bT2wQ9mXc7KdLz0RfVa1p","object":"rewrite","created":1767225600,"livemode":true,"replayed":false,"output":"Remote work runs on clear communication. At Acme Corp, teams that wrote things down shipped 23% faster.","words_in":34,"words_out":17,"sections":1,"warnings":[],"usage":{"words_charged":100,"balance":48212}}
To watch one from a terminal, add -N so curl shows each event as it comes:
curl -N https://slopmonkey.app/api/v1/rewrites \
-H "Authorization: Bearer $SLOPMONKEY_API_KEY" \
-H "Content-Type: application/json" \
-d '{"text": "In the ever-evolving landscape of remote work, it is important to note that clear communication plays a pivotal role in fostering collaboration.", "stream": true}'From your code
Keep each section’s text separately. On text.delta, add to that section; on section.reset, empty it. What you show is the sections joined in order.
// stream.mjs. Run it with: node stream.mjs (Node 20 or later)
async function rewriteStreaming(text, onText, idempotencyKey = crypto.randomUUID()) {
const res = await fetch("https://slopmonkey.app/api/v1/rewrites", {
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.SLOPMONKEY_API_KEY}`,
"Content-Type": "application/json",
"Idempotency-Key": idempotencyKey,
},
body: JSON.stringify({ text, stream: true }),
});
if (!res.ok) {
const { error } = await res.json();
throw new Error(`${error.code}: ${error.message}`);
}
const reader = res.body.pipeThrough(new TextDecoderStream()).getReader();
const parts = [];
let buffer = "";
for (;;) {
const { value, done } = await reader.read();
if (done) throw new Error("The stream ended early. Retry with the same Idempotency-Key.");
buffer += value;
let end;
while ((end = buffer.indexOf("\n\n")) >= 0) {
const block = buffer.slice(0, end);
buffer = buffer.slice(end + 2);
const event = block.match(/^event: (.*)$/m)?.[1];
const data = JSON.parse(block.match(/^data: (.*)$/m)?.[1] ?? "{}");
if (event === "text.delta") {
parts[data.section] = (parts[data.section] ?? "") + data.text;
onText(parts.join(""));
} else if (event === "section.reset") {
parts[data.section] = ""; // that section is being written again
onText(parts.join(""));
} else if (event === "rewrite.completed") {
return data; // data.output is the whole rewrite
} else if (event === "error") {
throw new Error(`${data.error.code}: ${data.error.message}`);
}
}
}
}
const result = await rewriteStreaming(
"In the ever-evolving landscape of remote work, it is important to note that clear communication plays a pivotal role in fostering collaboration.",
(soFar) => console.log(`${soFar.length} characters so far`),
);
console.log(result.output);# stream.py. Run it with: python stream.py (needs: pip install requests)
import json
import os
import uuid
import requests
def rewrite_streaming(text, on_text, idempotency_key=None):
with requests.post(
"https://slopmonkey.app/api/v1/rewrites",
headers={
"Authorization": f"Bearer {os.environ['SLOPMONKEY_API_KEY']}",
"Idempotency-Key": idempotency_key or str(uuid.uuid4()),
},
json={"text": text, "stream": True},
stream=True,
timeout=(10, 60), # a ping arrives at least every 15 seconds
) as response:
if not response.ok:
error = response.json()["error"]
raise RuntimeError(f"{error['code']}: {error['message']}")
parts, event = {}, None
for line in response.iter_lines(decode_unicode=True):
if line.startswith("event: "):
event = line[len("event: "):]
elif line.startswith("data: "):
data = json.loads(line[len("data: "):])
if event == "text.delta":
parts[data["section"]] = parts.get(data["section"], "") + data["text"]
on_text("".join(parts[i] for i in sorted(parts)))
elif event == "section.reset":
parts[data["section"]] = "" # that section is being written again
on_text("".join(parts[i] for i in sorted(parts)))
elif event == "rewrite.completed":
return data # data["output"] is the whole rewrite
elif event == "error":
raise RuntimeError(f"{data['error']['code']}: {data['error']['message']}")
raise RuntimeError("The stream ended early. Retry with the same Idempotency-Key.")
result = rewrite_streaming(
"In the ever-evolving landscape of remote work, it is important to note that clear "
"communication plays a pivotal role in fostering collaboration.",
lambda so_far: print(f"{len(so_far)} characters so far"),
)
print(result["output"])Usage
GET /api/v1/usage returns your API word balance and this calendar month’s use (UTC), for the account and for the key that asks. It takes no body and is free, but it counts toward the requests a minute, so call it at most once a minute.
{
"object": "usage",
"livemode": true,
"balance": { "words": 48212, "plan_words": 0, "purchased_words": 48212 },
"period": { "start": 1764547200, "end": 1767225600 },
"account": { "api_words": 21400, "api_requests": 133, "monthly_cap": null },
"key": { "id": "key_3hVq8ZtR1mWc", "name": "Production", "hint": "Qz9X", "api_words": 18600, "api_requests": 120, "monthly_cap": 50000 },
"limits": { "requests_per_minute": 60, "concurrent_requests": 2, "words_per_request": 5000, "minimum_words_per_request": 100 }
}| Field | Meaning |
|---|---|
balance.words | API words left. |
balance.plan_words | Always 0 in v1: there are no API subscriptions. Kept so the shape can grow. |
balance.purchased_words | API words bought in packs (or credited by Slop Monkey). They don’t expire. |
period | The current calendar month, UTC, in Unix seconds. |
account | This month’s API words and requests for the whole account, and its monthly cap (null for none). |
key | The same for the key that made this request, with its name and last 4 characters. |
limits | The limits on this key (Rate limits). |
Ping
GET /api/v1/ping checks that the API is up and, if you send a key, that it works. It never wakes the model and never charges.
curl https://slopmonkey.app/api/v1/ping \
-H "Authorization: Bearer $SLOPMONKEY_API_KEY"- Without a key:
{"object": "ping", "ok": true, "authenticated": false}. - With a working key:
{"object": "ping", "ok": true, "authenticated": true, "livemode": true, "key": {"id": "key_3hVq8ZtR1mWc", "name": "Production", "hint": "Qz9X"}}. - With a key that doesn’t work: the same 401 any endpoint gives.
Errors
Every error, on every endpoint and with every status, has the same shape:
{
"error": {
"type": "billing_error",
"code": "insufficient_words",
"message": "This request needs 1,240 words and the account has 800. Buy more at https://slopmonkey.app/api/keys. Nothing was charged.",
"param": null,
"doc_url": "https://slopmonkey.app/api/docs#insufficient_words"
},
"request_id": "req_9KcV3pWm2TqZx8Ld1RbNa4"
}codeis stable. Branch on it.typegroups codes for rough handling:invalid_request_error,authentication_error,permission_error,billing_error,idempotency_error,rate_limit_error,api_errororoverloaded_error.messageis for a person reading a log. It may change, so don’t match on it.paramnames the request field at fault, or isnull.doc_urllinks to the code’s entry below.
Mid-stream, the same object arrives as the data of an error event. No error is ever charged: any words held for the request go back before the error is sent. New codes may be added within v1, so treat a code you don’t know by its HTTP status.
Checks run in this order, so the first error you meet is the one to fix first: https, path and method, the key, a browser origin, content type and size, the JSON and its fields, the Idempotency-Key, rate and concurrency limits, the model’s capacity, then caps and balance.
Every code
https_required 400 · invalid_request_error
The request came over plain http. Nothing was done.
Use https://slopmonkey.app/api/v1/... . Requests over plain http are refused. If you sent a key, revoke it at https://slopmonkey.app/api/keys and make a new one.
Retry: no. Switch to https, and replace any key that was sent over http.
invalid_json 400 · invalid_request_error
The body isn’t valid JSON.
The request body isn’t valid JSON: Unexpected token } in JSON at position 41.
Retry: no. Fix the body.
missing_parameter 400 · invalid_request_error
A required field is missing. In v1 that is text.
`text` is required: the draft to rewrite, as a string.
Retry: no. Add the field.
invalid_parameter 400 · invalid_request_error
A field has the wrong type or a value that isn’t allowed: protect isn’t an array of strings, an entry is empty or over 400 characters, text holds a NUL or an unpaired surrogate, or include holds anything but "checks". param names the field.
`protect` must be an array of strings.
Retry: no. Fix the field.
unknown_parameter 400 · invalid_request_error
The body has a field the API doesn’t know. Usually a typo.
Unknown parameter `protected`. Did you mean `protect`?
Retry: no. Rename or remove the field.
text_empty 400 · invalid_request_error
text has no words in it, for example only spaces or punctuation.
`text` has no words in it.
Retry: no.
text_too_long 400 · invalid_request_error
text has more than 5,000 words.
`text` is 6,240 words. The limit is 5,000 a request. Split it at a paragraph break and send the parts as separate requests.
Retry: no. Split the text and send the parts.
too_many_protected 400 · invalid_request_error
protect has more than 50 entries.
`protect` has 64 entries. The limit is 50.
Retry: no. Keep the 50 that matter most.
idempotency_key_invalid 400 · idempotency_error
The Idempotency-Key header is empty, longer than 255 characters, or holds characters other than printable ASCII.
`Idempotency-Key` must be 1 to 255 printable ASCII characters. A UUID is ideal.
Retry: no. Use a UUID.
missing_api_key 401 · authentication_error
No key arrived in Authorization: Bearer. The message names the usual mistakes: a key without the word Bearer, a key in another header or in the query string, or a key from another service.
No API key was sent. Send it as `Authorization: Bearer sm_live_...`. Create one at https://slopmonkey.app/api/keys.
Retry: no. Send the header.
invalid_api_key 401 · authentication_error
The key isn’t one of ours. If its checksum fails, the message says it has a typo.
This API key has a typo: its last 6 characters don’t match the rest. Copy it again from where you saved it.
Retry: no. Copy the key again, or make a new one.
revoked_api_key 401 · authentication_error
The key was revoked on the keys page.
This API key ("Laptop", ending Qz9X) was revoked on 3 December 2026. Create a new one at https://slopmonkey.app/api/keys.
Retry: no. Use another key.
insufficient_words 402 · billing_error
The account doesn’t have enough API words for this request. A request needs the words in its text, at least 100. Nothing was taken.
This request needs 1,240 words and the account has 800. Buy more at https://slopmonkey.app/api/keys. Nothing was charged.
Retry: not until API words are bought on the keys page.
spend_cap_reached 402 · billing_error
The request would pass a monthly word cap set on the keys page, for this key or for the whole account. Caps reset on the 1st of each month, UTC.
This key has used 49,800 of its 50,000-word monthly cap and this request needs 400. Raise the cap at https://slopmonkey.app/api/keys or wait until 1 January 2027 (UTC).
Retry: not until a person raises the cap or the month turns. Don’t retry in a loop.
browser_not_allowed 403 · permission_error
The request came from a web page (it carried a browser’s Origin header). A key in a page can be read by anyone who opens it.
API keys can’t be used from a web page, where anyone can read them. Call the API from your server and send the result to your page.
Retry: no. Call the API from your server.
account_suspended 403 · permission_error
The account is suspended, or its API access is paused. All of its keys get this answer.
This account is suspended. If you think that is a mistake, write to support@slopmonkey.app.
Retry: no. Write to support@slopmonkey.app.
not_found 404 · invalid_request_error
No endpoint at that path.
No such endpoint: GET /api/v1/rewrite. Did you mean POST /api/v1/rewrites? Reference: https://slopmonkey.app/api/docs
Retry: no. Fix the path.
method_not_allowed 405 · invalid_request_error
The path exists but takes another method. The Allow header lists the right one.
/api/v1/rewrites takes POST, not GET.
Retry: no. Use the method in Allow.
idempotency_in_progress 409 · idempotency_error
A request with this Idempotency-Key is still running.
A request with this Idempotency-Key is still running. Retry after 20 seconds and you’ll get its result or a free repeat.
Retry: yes, after Retry-After seconds, with the same key.
idempotency_key_exhausted 409 · idempotency_error
This Idempotency-Key has already been repeated 3 times at no charge.
This Idempotency-Key has already been repeated 3 times. Use a new key for a new request.
Retry: only with a new key, which is charged as a new request.
request_too_large 413 · invalid_request_error
The body is over 128 KB. It was refused without being read.
The request body is 210 KB. The limit is 128 KB.
Retry: no. Send a smaller body.
unsupported_media_type 415 · invalid_request_error
The body wasn’t sent as JSON.
Send the body as JSON with `Content-Type: application/json`.
Retry: no. Set the header.
idempotency_key_reused 422 · idempotency_error
This Idempotency-Key was used in the last 24 hours with a different request body.
This Idempotency-Key was used for a different request in the last 24 hours. Use a new key for each new request.
Retry: only with a new key.
rate_limited 429 · rate_limit_error
The account has made its requests for this minute: 60 with live keys, 30 with test keys.
Too many requests: this account’s limit is 60 a minute. Retry after 23 seconds.
Retry: yes, after Retry-After seconds.
concurrency_limited 429 · rate_limit_error
The account already has 2 rewrites running.
This account already has 2 rewrites running, its limit. Retry when one finishes.
Retry: yes, after Retry-After seconds, or when one of your rewrites finishes.
internal_error 500 · api_error
Something went wrong on our side. Nothing was charged.
Something went wrong on our side. Nothing was charged. Retry, and if it keeps happening write to support@slopmonkey.app with this request_id.
Retry: yes, with a growing wait, and the same Idempotency-Key.
overloaded 503 · overloaded_error
The share of the model kept for the API is busy. Nothing was charged.
The model is busy. Nothing was charged. Retry after 10 seconds.
Retry: yes, after Retry-After seconds, with the same Idempotency-Key.
timeout 504 · api_error
The rewrite took longer than 280 seconds and was stopped. Nothing was charged.
The rewrite took longer than 280 seconds and was stopped. Nothing was charged. Retry, or use stream: true.
Retry: yes, or send shorter parts, or use "stream": true.
Rate limits
Limits belong to the account, not the key, so more keys don’t raise them. Keys can only narrow things, through the caps you set.
| Limit | Value | When it is reached |
|---|---|---|
| Requests a minute, live keys | 60 for the account | 429 rate_limited |
| Requests a minute, test keys | 30 for the account, counted apart from live | 429 rate_limited |
| Rewrites running at once | 2 for the account | 429 concurrency_limited |
| Words a request | 5,000 | 400 text_too_long |
| Body size | 128 KB | 413 request_too_large |
| Time for one request | 280 seconds | 504 timeout |
| Monthly word cap, per key | None unless you set one | 402 spend_cap_reached |
| Monthly word cap, account | None unless you set one | 402 spend_cap_reached |
| Active keys | 10 for the account | The keys page won’t make more |
Every request counts once against the minute, whatever its length, and usage and ping count too. The minute is a calendar minute.
Every answer to a request with a key carries:
RateLimit-Limit: requests allowed a minute.RateLimit-Remaining: requests left this minute.RateLimit-Reset: seconds until the count starts again.
Retry-After, in seconds, comes with every 429 and 503, and with 409 idempotency_in_progress. When many people use the API at once, its share of the model can fill up: that answer is 503 overloaded, and waiting Retry-After seconds is enough.
Set your client’s timeout to at least 300 seconds, or use "stream": true. Caps answer 402, not 429, because waiting won’t help: a person has to raise the cap or wait for the month to turn.
Retrying
Retry only the codes that say so, wait as long as Retry-After asks, and keep the same Idempotency-Key for every try of the same text, so a retry is never charged twice.
const RETRY = new Set([
"rate_limited", "concurrency_limited", "idempotency_in_progress",
"overloaded", "model_unavailable", "internal_error", "timeout",
]);
const sleep = (seconds) => new Promise((resolve) => setTimeout(resolve, seconds * 1000));
async function rewrite(body, tries = 5) {
const idempotencyKey = crypto.randomUUID(); // one key for every try of this text
for (let attempt = 1; ; attempt++) {
let res;
try {
res = await fetch("https://slopmonkey.app/api/v1/rewrites", {
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.SLOPMONKEY_API_KEY}`,
"Content-Type": "application/json",
"Idempotency-Key": idempotencyKey,
},
body: JSON.stringify(body),
});
} catch (err) {
// The connection dropped: the same key gets the rewrite without a second charge
if (attempt >= tries) throw err;
await sleep(2 ** attempt);
continue;
}
const data = await res.json();
if (res.ok) return data;
if (!RETRY.has(data.error.code) || attempt >= tries) {
throw new Error(`${data.error.code}: ${data.error.message}`);
}
await sleep(Number(res.headers.get("Retry-After")) || 2 ** attempt);
}
}
const result = await rewrite({ text: "In the ever-evolving landscape of remote work, it is important to note that clear communication plays a pivotal role in fostering collaboration." });
console.log(result.output);import os
import time
import uuid
import requests
RETRY = {
"rate_limited", "concurrency_limited", "idempotency_in_progress",
"overloaded", "model_unavailable", "internal_error", "timeout",
}
def rewrite(body, tries=5):
idempotency_key = str(uuid.uuid4()) # one key for every try of this text
for attempt in range(1, tries + 1):
try:
response = requests.post(
"https://slopmonkey.app/api/v1/rewrites",
headers={
"Authorization": f"Bearer {os.environ['SLOPMONKEY_API_KEY']}",
"Idempotency-Key": idempotency_key,
},
json=body,
timeout=300,
)
except (requests.ConnectionError, requests.Timeout):
# The connection dropped: the same key gets the rewrite without a second charge
if attempt == tries:
raise
time.sleep(2 ** attempt)
continue
data = response.json()
if response.ok:
return data
code = data["error"]["code"]
if code not in RETRY or attempt == tries:
raise RuntimeError(f"{code}: {data['error']['message']}")
time.sleep(int(response.headers.get("Retry-After", 2 ** attempt)))
result = rewrite({"text": "In the ever-evolving landscape of remote work, it is important to note that "
"clear communication plays a pivotal role in fostering collaboration."})
print(result["output"])Idempotency
Send an Idempotency-Key header with every rewrite: 1 to 255 printable ASCII characters, ideally a UUID. Make one for each piece of text and reuse it whenever you retry that text. It is accepted on POST /api/v1/rewrites and ignored elsewhere. We remember it for 24 hours from its first use, separately for live and test keys.
What happens when a key comes again:
- A new key: the request runs as normal.
- The same key with a different body: 422
idempotency_key_reused. - The same key while the first request is still running: 409
idempotency_in_progress, withRetry-After. - The same key after the first request failed with an error: it runs again as if new. The error was not charged, so this one is charged as normal if it works.
- The same key after the first request finished, or after it was cut off: the same text is rewritten again, at no charge, and the answer says
"replayed": truewithwords_charged0. This happens up to 3 times; the fourth gets 409idempotency_key_exhausted.
We don’t keep your text or the rewrite, so a repeat is a fresh rewrite, not a copy: its wording differs from the first. If you never received the first answer, that makes no difference.
A request refused before it starts (a bad field, a bad key, a rate limit, too few words) does not use up its key, so you can fix the cause and send it again with the same key. After 24 hours the key is forgotten, and the same key starts a new, charged request.
Billing
API words. The API spends from a balance of API words, bought in packs on the keys page, through Stripe’s checkout. They are in the balance a few seconds after you pay. API words never expire. They are separate from the words used in the Slop Monkey app: neither can be spent on the other, and nothing is free except the 2,000 free words added once, when an account first opens the keys page.
| Pack | Price | API words |
|---|---|---|
| Starter | $10 | 40,000 |
| Growth | $50 | 250,000 |
| Scale | from $200 | 1,250,000, by arrangement |
| Volume | Ask | 8,000,000 and up, by arrangement |
For Scale and Volume, talk to us. By buying you agree to the API terms and the acceptable-use policy.
What a word is. Words are counted as the word counter in the app counts them: each run of letters or digits is one word, with apostrophes and hyphens inside it, and each Chinese, Japanese or Korean character is one word.
| Text | Words |
|---|---|
don't | 1 |
state-of-the-art | 1 |
Acme Corp shipped 23% faster. | 5 |
远程工作 | 4 |
What a request costs. The words in text, with a minimum of 100 a request. Protected terms and quotations count, since they are part of the text. The words you get back are never charged.
When. The words are held when the request is admitted, after its key, fields, limits, caps and balance have been checked, and charged when the rewrite finishes:
- It works: you are charged for the sections that were rewritten, at least 100. Sections returned unchanged (
section_unchanged) are free. Anything held beyond that goes back before the answer is sent. - It ends in an error, as an error response or an
errorevent: everything held goes back. No error is ever charged. - The connection drops before the answer arrives: the rewrite most likely finished, and it was charged. Retry with the same Idempotency-Key within 24 hours and it is rewritten again at no charge.
Running out. The whole charge is held up front, so a request can’t run out halfway. It either starts with its words held or is refused with 402 insufficient_words and nothing taken. With fewer than 100 API words left, every request is refused until you buy more.
Caps. On the keys page you can set a monthly word cap on any key and on the whole account. A request that would pass a cap gets 402 spend_cap_reached.
Test mode
A test key (sm_test_) is free for any signed-in account. It goes through the same checks, errors, headers, idempotency and streaming as a live key, but:
- the rewrite comes from a rough stand-in that swaps some words for synonyms, at once, instead of the real model;
- nothing is charged, and the response shows what a live request would have charged;
livemodeisfalse;- it has its own limit of 30 requests a minute;
- it accepts the
Slopmonkey-Testheader.
With Slopmonkey-Test you can make a request take a path on purpose, to try your error handling. Its value is any error code on this page, answered with its real status, headers and message, or one of these:
| Value | What happens |
|---|---|
an error code, such as insufficient_words | That error, exactly as a live request would get it. |
section_reset | A stream sends a section.reset for section 0, then finishes normally. |
mid_stream_error | A stream sends some deltas, then an error event with model_unavailable. |
slow | About 20 seconds of ping events before the first delta. |
curl https://slopmonkey.app/api/v1/rewrites \
-H "Authorization: Bearer $SLOPMONKEY_TEST_KEY" \
-H "Content-Type: application/json" \
-H "Slopmonkey-Test: insufficient_words" \
-d '{"text": "A short draft to test with."}'The header is ignored with a live key.
Text and languages
- Plain text. Send plain text. Markdown and HTML are treated as words, so symbols and tags may be reworded or dropped. Strip markup first, or list what must survive in
protect. - Line breaks are kept, and come back as
\n. Emoji and accents pass through unchanged. - Languages. English and Chinese. Other languages are accepted and charged, but the results are not good and are not supported. If a rewrite drifts into the wrong language, that section is written again by itself (a
section.resetwithlanguage). - Long text. Up to 5,000 words a request. Text over about 370 words is cut into sections at paragraph or sentence breaks, rewritten in parallel and joined with the original whitespace. For more than 5,000 words, split at paragraph breaks, send each part as its own request, and join the results.
- Check what comes back. The model can change a meaning or get a detail wrong. If a rewrite will be published or sent to someone, have a person read it first, and treat it as text from outside your system.
Privacy
The text you send and the rewrite we return pass through our servers and our model server (Modal, in the United States). They are not saved, logged or used to train any model.
For each request we keep a record without its text: which of your keys made it, when, how many words it had and was charged, whether it worked and its error code if not, its request id, and how long it took. If you send an Idempotency-Key, we keep it for 24 hours with a keyed fingerprint of the request, which can’t be turned back into your text, so a repeat is never charged twice. API keys are stored only as a one-way hash.
If the text you send is about your own users, we handle it on your behalf, only to make the rewrite you asked for. The privacy policy has the rest, and the API terms cover what each of us is responsible for.
Versions and changes
The major version is in the path: /api/v1. Within v1 we only add things: new optional request fields, new response fields, new event types, new error codes and new endpoints. A client that ignores what it doesn’t recognise keeps working.
Anything that would break a working client ships as v2, at a new path. We announce it by email to every account with a key at least 6 months ahead, and keep v1 running for at least 12 months after v2 launches.
Changelog
- v1.0.0: first release.
POST /rewrites(with streaming),GET /usageandGET /ping.
APIAPI keysOpenAPIAPI termsAcceptable usesupport@slopmonkey.app