# Translation tools

> Make extra content from a finished translation: a Persian summary (free), slides (PPTX and PDF), a mind map, LinkedIn posts, and proofreading suggestions. Each tool is a synchronous call on the translation's `jobId`, for example `POST /api/v1/translate/{jobId}/slides`: POST makes and saves a result (paid tools charge Fara), GET on the same path reads the saved result for free, DELETE removes it. The summary is free and already made.

## At a glance

- Base path: `https://faraatarjomeh.com/api/v1/translate/{jobId}/…` — `jobId` is the UUID of a PDF translation ([PDF translation](https://faraatarjomeh.com/api/v1/docs/guides/pdf-translation.md)).
- Needs: the translation job must be `completed` or `completed_partial` to make anything (`400` otherwise). Reading and deleting work on any of your jobs.
- Auth: `Authorization: Bearer $FARA_API_KEY`. Scope `read` for GET, `write` for POST and DELETE.
- Spends Fara: `POST /api/v1/translate/{jobId}/slides`, `POST /api/v1/translate/{jobId}/mindmap`, `POST /api/v1/translate/{jobId}/linkedin`, `POST /api/v1/translate/{jobId}/proofread`. Free: the summary, all GET and DELETE calls, and the file exports (slide files, mind map PDF, summary PDF).
- Async: no. Each POST answers when the result is ready. It can take several minutes (see [Timeouts](#timeouts-and-recovery)).
- Idempotent: **no**, not by themselves. Every POST makes a new result, replaces the saved one, and charges again. Always send an `Idempotency-Key`.
- Webhooks: none. The answer of the POST is the result.
- Podcast and audiobook are separate background jobs: [Podcast and audiobook](https://faraatarjomeh.com/api/v1/docs/guides/podcast-audiobook.md).

| Tool | Make | Read saved | Delete | Files | Cost |
|---|---|---|---|---|---|
| Summary | made with the translation | `GET /api/v1/translate/{jobId}/summary` | `DELETE /api/v1/translate/{jobId}/summary` | `POST /api/v1/translate/{jobId}/summary/pdf` | free |
| Slides | `POST /api/v1/translate/{jobId}/slides` | `GET /api/v1/translate/{jobId}/slides` | `DELETE /api/v1/translate/{jobId}/slides` | `POST /api/v1/translate/{jobId}/slides/generate-files`, then download `slides-pptx`, `slides-pdf` | actual cost |
| Mind map | `POST /api/v1/translate/{jobId}/mindmap` | `GET /api/v1/translate/{jobId}/mindmap` | `DELETE /api/v1/translate/{jobId}/mindmap` | `POST /api/v1/translate/{jobId}/mindmap/pdf` | actual cost |
| LinkedIn posts | `POST /api/v1/translate/{jobId}/linkedin` | `GET /api/v1/translate/{jobId}/linkedin` | `DELETE /api/v1/translate/{jobId}/linkedin` | — | actual cost |
| Proofreading | `POST /api/v1/translate/{jobId}/proofread` | `GET /api/v1/translate/{jobId}/proofread` | `DELETE /api/v1/translate/{jobId}/proofread` | — | actual cost; currently switched off |

## Billing

For slides, mind map, LinkedIn posts and proofreading:

1. Before anything runs, an estimate is held. It is based on the length of the translated text (at least 1 Fara). Not enough Fara → `402 INSUFFICIENT_CREDITS` with `balance` and `estimatedCost`; nothing is held and nothing runs.
2. After the result is made, the actual cost is charged and the rest of the hold comes back. The answer has `faraCost` (Fara charged) and `billing: "charged"`.
3. If making the result fails, you pay only for the work already done in that call; if none was done, the hold is released in full.

### Price first (switch on)

Only while the price-first switch is on (it is off by default, so check it before you rely on it). This applies to slides, mind map and LinkedIn posts. Proofreading is not affected.

- `GET /api/v1/translate/{jobId}/tools/price` returns `jobId`, `capped: true` and `tools` for `slides`, `mindmap` and `linkedin`. Each tool has `available`; when it is `true` it also has `faraCharged`, the Fara the POST would hold (0 when the account is not billed). A tool with `available: false` has too little text to make, and its POST answers 400. If no tool is available the price call itself answers 400. It is free and holds nothing.
- A `404` with code `FEATURE_DISABLED` from the price call means price-first is off on this server. Then use the normal flow below, without `maxFara`.
- Send `maxFara` (a number of Fara, 0 or more) in the POST body. If the price is now above it, the answer is `409` with code `PRICE_CHANGED` and `faraCharged` (the new price). Nothing is held. A `maxFara` that is not a number of 0 or more answers `400` with code `INVALID_MAX_FARA`. Show the new price to the user, and resend with the same `Idempotency-Key` and a `maxFara` they agreed to.
- Without `maxFara`, the POST still runs. The charge is still never more than the held amount.
- If the price rises between the price call and the POST, the hold is given back and the answer is `409` `PRICE_CHANGED` with the new price.
- The charge never goes above the amount held. The answer has `heldFara` (held before the work) and `refundedFara` (given back from the hold).
- While the switch is off, `maxFara` is ignored and the answers have no `heldFara` or `refundedFara`.

To see what a call cost, read `faraCost` in its answer, or the ledger with `GET /api/v1/account/transactions` and `?jobId={jobId}` (tool rows have ids such as `slides-<jobId>-<time>`; `relatedJobId` is the translation's `jobId`).

`GET` of a saved result always shows `faraCost: 0` and `billing: "included_in_translation"`. It does not repeat what the POST cost.

### Always send an Idempotency-Key

A tool POST has no duplicate guard of its own. Two POSTs make two results and two charges.

- Send `Idempotency-Key: <new UUID>` on every tool POST, and keep the key until you have the answer.
- If the request times out or the connection drops, send it again with the **same** key. While the first call still runs you get `409 IDEMPOTENCY_KEY_IN_USE` (wait `Retry-After`, send again). When it has finished you get its stored answer with `Idempotent-Replayed: true`. Nothing is made or charged twice.
- If the resend answers `409 IDEMPOTENCY_KEY_ALREADY_USED` with `originalStatus: 200`, the first answer was too large to store. The result was made and saved: read it with the tool's `GET`.
- Use a **new** key only when you really want a new result and a new charge.

## Timeouts and recovery

- Each attempt to make a result may take up to 10 minutes. When the result comes back unusable, the server tries again, up to 3 attempts in one call. Set your client timeout to **30 minutes**.
- `504 UPSTREAM_TIMEOUT`: making the result took too long. Nothing was saved; work already done may be charged. This answer is stored under your key: to try again, first `GET` the tool (to confirm nothing was saved), then POST with a **new** key.
- `502 UPSTREAM_ERROR`: the result came back empty. Nothing was saved. Try again once with a new key after 1 minute.
- The answer may carry `warnings: [{"code": "DERIVED_CONTENT_PARTIAL", "message": "…", "messageFa": "…"}]`: part of the result did not come back in the expected shape and may be missing. The result is saved and charged.
- `saved: false` with `warning`: the result was made and charged but not saved. Keep the answer; `GET` will not return it.

## Summary (free)

A Persian summary of the document is made during the translation and is included in its price. There is nothing to generate and nothing to charge.

```http
GET /api/v1/translate/3f1c2b7e-9a4d-4c1e-8f7a-2b9c4d5e6f70/summary HTTP/1.1
Authorization: Bearer fara_sk_...
```

Response `200 OK`:

```json
{
  "hasSummary": true,
  "hasDigest": true,
  "jobId": "3f1c2b7e-9a4d-4c1e-8f7a-2b9c4d5e6f70",
  "digest": "# رهبری در عمل\n\nاین کتاب نشان می‌دهد که چرا چشم‌انداز رهبران اغلب به کارکنان نمی‌رسد...",
  "digestChars": 18342,
  "coverage": "full",
  "truncated": false,
  "faraCost": 0,
  "billing": "included_in_translation",
  "savedAt": "2026-09-25T21:12:40.551Z"
}
```

```bash
curl -s "https://faraatarjomeh.com/api/v1/translate/$JOB_ID/summary" -H "Authorization: Bearer $FARA_API_KEY"
```

| Field | Type | Meaning |
|---|---|---|
| `hasSummary`, `hasDigest` | boolean | `true` when a summary exists. |
| `digest` | string | The summary, Persian Markdown. |
| `digestChars` | integer | Length of `digest`. |
| `coverage` | string | `full`, or `partial` when only part of the document was summarized. |
| `truncated` | boolean | `true` when the summary was cut short. |
| `status` | string or null | Only when there is no summary: `null` (not made yet) or `skipped`. |
| `brief` | object or null | The short card: `title`, `kind`, `summary`, `points` (3 to 5 short ideas), `takeaway`, `audience`. `null` until it is ready. |
| `briefStatus` | string | `ready`, `preparing` (being made in the background now; ask again in a few seconds), or `unavailable` (could not be made). |

No summary yet → `200` with `hasSummary: false`, `hasDigest: false`, and `status`. A summary can be `skipped` (for example, when the document has too little text); then none will come.

Related calls:

- `GET /api/v1/translate/{jobId}/digest` returns the same summary (without `hasSummary`; with `reason` when it is missing), including `brief` and `briefStatus`.
- `GET /api/v1/translate/{jobId}/summary-card?format=png` (or `format=pdf`) returns a one-page card of the brief summary, as `image/png` (default) or `application/pdf`. Free. Answers `409` with `code: SUMMARY_NOT_READY` while the brief is still being made; ask again in a few seconds.
- `POST /api/v1/translate/{jobId}/summary` returns the same answer as `GET` (plus `saved: true`), or `404` when there is no summary. It is free and makes nothing. Kept for older clients.
- `POST /api/v1/translate/{jobId}/summary/pdf` returns the summary as a PDF (`application/pdf`). Free. Body (optional): `title` (string), `showHeader` (boolean, default `true`), `styles` (object, as in [custom PDF](https://faraatarjomeh.com/api/v1/docs/guides/pdf-translation.md#custom-styled-pdf)). `404` when there is no summary.
- `DELETE /api/v1/translate/{jobId}/summary` does **not** remove the summary made with the translation; `GET` keeps returning it.

## Slides

### 1. Choose design styles (optional)

`GET /api/v1/translate/slides/design-styles`:

```json
{
  "pptx": {
    "defaultStyle": "memphis",
    "styles": [
      { "id": "memphis", "label": "Minimal", "labelFa": "مینیمال", "description": "Clean minimal deck with a subtle brand accent.", "descriptionFa": "طرح تمیز و مینیمال با نشان ظریف برند." },
      { "id": "neo", "label": "Sadeh", "labelFa": "ساده", "description": "Clean bright deck for reports and workshops.", "descriptionFa": "طرح روشن و تمیز برای گزارش‌ها و کارگاه‌ها." }
    ]
  },
  "pdf": {
    "defaultStyle": "memphis",
    "styles": [
      { "id": "memphis", "label": "Minimal", "labelFa": "مینیمال", "description": "Clean minimal deck with a subtle brand accent.", "descriptionFa": "طرح تمیز و مینیمال با نشان ظریف برند." },
      { "id": "neo", "label": "Sadeh", "labelFa": "ساده", "description": "Light and clean slides for classes and reports.", "descriptionFa": "طرح روشن و تمیز برای کلاس و گزارش." }
    ]
  },
  "pricing": {
    "pdfStyleCostFara": 0,
    "message": "Slides generation is billed at its actual AI cost. Exporting files and changing PDF style are free.",
    "messageFa": "تولید اسلاید بر اساس هزینه واقعی هوش مصنوعی محاسبه می‌شود. خروجی گرفتن فایل‌ها و تغییر استایل PDF رایگان است."
  }
}
```

(Style lists shortened.) Style ids today: `memphis` (default), `neo`, `noir`, `aurora`, for both PPTX and PDF. Read them from this call rather than hard-coding them.

### 2. Make the slides (paid)

`POST /api/v1/translate/{jobId}/slides`. No body. Needs at least 50 characters of Persian text (`400` otherwise).

```http
POST /api/v1/translate/3f1c2b7e-9a4d-4c1e-8f7a-2b9c4d5e6f70/slides HTTP/1.1
Authorization: Bearer fara_sk_...
Idempotency-Key: 4b7e2d19-8c3a-4f65-a0d2-7e9c1b5f3a80
```

Response `200 OK` (slide list shortened to two items):

```json
{
  "jobId": "3f1c2b7e-9a4d-4c1e-8f7a-2b9c4d5e6f70",
  "slides": [
    {
      "slideNumber": 1,
      "slideType": "title",
      "title": "رهبری در عمل",
      "subtitle": "چرا چشم‌انداز به کارکنان نمی‌رسد",
      "body": [],
      "notes": "معرفی کتاب و پرسش اصلی آن."
    },
    {
      "slideNumber": 2,
      "slideType": "content",
      "title": "شکاف میان چشم‌انداز و اجرا",
      "subtitle": "",
      "body": [
        { "text": "رهبران به‌ندرت از نداشتن چشم‌انداز شکست می‌خورند", "bold": true, "indent": 0, "column": "" },
        { "text": "مشکل در رساندن آن به افرادی است که کار را انجام می‌دهند", "bold": false, "indent": 1, "column": "" }
      ],
      "notes": "با یک مثال از فصل اول شروع کنید."
    }
  ],
  "metadata": { "totalSlides": 18, "bookTitle": "رهبری در عمل", "estimatedDuration": "۲۰ دقیقه" },
  "processedAt": "2026-09-26T08:15:02.310Z",
  "faraCost": 3,
  "billing": "charged",
  "saved": true
}
```

```bash
curl -s --max-time 1800 -X POST "https://faraatarjomeh.com/api/v1/translate/$JOB_ID/slides" \
  -H "Authorization: Bearer $FARA_API_KEY" \
  -H "Idempotency-Key: $(uuidgen)"
```

| Slide field | Type | Values |
|---|---|---|
| `slideNumber` | integer | 1, 2, … |
| `slideType` | string | `title`, `section_divider`, `content`, `two_column`, `summary` |
| `title`, `subtitle`, `notes` | string | Persian; `subtitle` and `notes` can be empty |
| `body[]` | array | `text` (string), `bold` (boolean), `indent` (0–2), `column` (`""`, `right`, `left`; used by `two_column`) |

A deck has up to about 35 slides.

### 3. Make the files (free)

`POST /api/v1/translate/{jobId}/slides/generate-files` builds a PPTX and a PDF from the saved slides. Body (optional): `pptxStyle`, `pdfStyle` (ids from step 1). An unknown id falls back to the last used style, then to the default. `404` when there are no saved slides. Calling it again replaces the files.

```http
POST /api/v1/translate/3f1c2b7e-9a4d-4c1e-8f7a-2b9c4d5e6f70/slides/generate-files HTTP/1.1
Authorization: Bearer fara_sk_...
Content-Type: application/json

{"pptxStyle": "neo", "pdfStyle": "neo"}
```

Response `200 OK`:

```json
{
  "jobId": "3f1c2b7e-9a4d-4c1e-8f7a-2b9c4d5e6f70",
  "pptxFileId": "66f2c4d1e2f3a4b5c6d7e8f9",
  "slidesPdfFileId": "66f2c4d1e2f3a4b5c6d7e8fa",
  "styles": { "pptxStyle": "neo", "pdfStyle": "neo" },
  "faraCost": 0,
  "pptxSize": 1482231,
  "slidesPdfSize": 2210458,
  "generated": true
}
```

```bash
curl -s -X POST "https://faraatarjomeh.com/api/v1/translate/$JOB_ID/slides/generate-files" \
  -H "Authorization: Bearer $FARA_API_KEY" -H "Content-Type: application/json" \
  -d '{"pptxStyle":"neo","pdfStyle":"neo"}'
```

### 4. Download (free)

`GET /api/v1/translate/download/{jobId}/{type}` with `type`:

| `type` | Content-Type |
|---|---|
| `slides-pptx` | `application/vnd.openxmlformats-officedocument.presentationml.presentation` |
| `slides-pdf` | `application/pdf` |

`404` ("Generate files first") when step 3 has not run.

```bash
curl -sf -o slides.pptx "https://faraatarjomeh.com/api/v1/translate/download/$JOB_ID/slides-pptx" \
  -H "Authorization: Bearer $FARA_API_KEY"
```

### Read or delete

- `GET /api/v1/translate/{jobId}/slides` → `hasSlides: false` when none; otherwise `hasSlides: true`, `slides`, `metadata`, `processedAt`, `savedAt`, `pptxFileId`, `slidesPdfFileId`, `filesGeneratedAt`.
- `DELETE /api/v1/translate/{jobId}/slides` removes the slides and their files. Answer: `{"jobId": "…", "deleted": true, "message": "Slides data deleted"}`.

## Mind map

### Make it (paid)

`POST /api/v1/translate/{jobId}/mindmap`. No body. Needs at least 50 characters of Persian text.

```http
POST /api/v1/translate/3f1c2b7e-9a4d-4c1e-8f7a-2b9c4d5e6f70/mindmap HTTP/1.1
Authorization: Bearer fara_sk_...
Idempotency-Key: e1c7a3b5-9d2f-4a68-8b04-3f6e2d9c1a57
```

Response `200 OK` (tree shortened):

```json
{
  "jobId": "3f1c2b7e-9a4d-4c1e-8f7a-2b9c4d5e6f70",
  "hasMindmap": true,
  "title": "رهبری در عمل",
  "root": {
    "id": "root",
    "label": "رهبری در عمل",
    "summary": "چرا چشم‌انداز رهبران به کارکنان نمی‌رسد و چه باید کرد.",
    "children": [
      {
        "id": "n1",
        "label": "شکاف اجرا",
        "summary": "فاصله میان تصمیم و عمل.",
        "children": [
          { "id": "n1-1", "label": "پیام‌های مبهم", "summary": "هدف‌ها روشن بیان نمی‌شوند.", "children": [] }
        ]
      }
    ]
  },
  "nodeCount": 37,
  "metadata": { "language": "fa", "nodeCount": 37, "maxDepth": 4 },
  "processedAt": "2026-09-26T08:21:47.902Z",
  "faraCost": 2,
  "billing": "charged",
  "saved": true
}
```

```bash
curl -s --max-time 1800 -X POST "https://faraatarjomeh.com/api/v1/translate/$JOB_ID/mindmap" \
  -H "Authorization: Bearer $FARA_API_KEY" \
  -H "Idempotency-Key: $(uuidgen)"
```

Each node: `id` (string, unique), `label` (string), `summary` (string), `children` (array of nodes). The tree is at most 5 levels deep.

### Get it as a PDF (free)

1. `GET /api/v1/translate/mindmap/spec` lists color sets: `colorHarmonies[]` with `id`, `label`, `labelFa`, `canvasBg`, `linkColor`, `swatches`, `nodeColors`. Ids today: `sage`, `ocean`, `sunset`, `lavender`.
2. `POST /api/v1/translate/{jobId}/mindmap/pdf` with optional body `{"title": "…", "harmonyId": "ocean"}`. Returns the PDF (`application/pdf`) directly. An unknown `harmonyId` uses the default colors. `404` when there is no saved mind map. The answer is a file: do not send an `Idempotency-Key`.

```bash
curl -sf -o mindmap.pdf -X POST "https://faraatarjomeh.com/api/v1/translate/$JOB_ID/mindmap/pdf" \
  -H "Authorization: Bearer $FARA_API_KEY" -H "Content-Type: application/json" \
  -d '{"harmonyId":"ocean"}'
```

### Read or delete

- `GET /api/v1/translate/{jobId}/mindmap` → `hasMindmap: false` when none; otherwise `title`, `root`, `nodeCount`, `metadata`, `processedAt`, `savedAt`.
- `DELETE /api/v1/translate/{jobId}/mindmap` → `{"jobId": "…", "deleted": true, "message": "Mindmap deleted"}`.

## LinkedIn posts

`POST /api/v1/translate/{jobId}/linkedin` (paid). No body. Needs at least 100 characters of Persian text. Asks for 10 posts; the answer can hold fewer.

```http
POST /api/v1/translate/3f1c2b7e-9a4d-4c1e-8f7a-2b9c4d5e6f70/linkedin HTTP/1.1
Authorization: Bearer fara_sk_...
Idempotency-Key: 2d9f4a61-7b3c-4e18-9a5d-0c8e6f2b4d73
```

Response `200 OK` (posts shortened to one):

```json
{
  "jobId": "3f1c2b7e-9a4d-4c1e-8f7a-2b9c4d5e6f70",
  "totalPosts": 10,
  "processedAt": "2026-09-26T08:30:11.004Z",
  "posts": [
    {
      "id": 1,
      "theme": "شکاف میان چشم‌انداز و اجرا",
      "target_audience": "مدیران میانی",
      "format_type": "story",
      "word_count": 142,
      "content": "سال گذشته در جلسه‌ای بودم که مدیرعامل چشم‌اندازی درخشان ارائه داد..."
    }
  ],
  "metadata": {},
  "faraCost": 2,
  "billing": "charged",
  "saved": true
}
```

```bash
curl -s --max-time 1800 -X POST "https://faraatarjomeh.com/api/v1/translate/$JOB_ID/linkedin" \
  -H "Authorization: Bearer $FARA_API_KEY" \
  -H "Idempotency-Key: $(uuidgen)"
```

| Post field | Type | Values |
|---|---|---|
| `id` | integer | 1, 2, … |
| `theme`, `target_audience`, `content` | string | Persian |
| `format_type` | string | `story`, `data-insight`, `framework`, `reflective`, `provocative` |
| `word_count` | integer | approximate words in `content` |

- `GET /api/v1/translate/{jobId}/linkedin` → `saved: false` and `posts: []` when none; otherwise `totalPosts`, `posts`, `processedAt`, `savedAt`, `saved: true`.
- `DELETE /api/v1/translate/{jobId}/linkedin` → `{"jobId": "…", "deleted": true, "message": "LinkedIn posts deleted"}`.

## Proofreading

`POST /api/v1/translate/{jobId}/proofread` (paid) returns suggested edits to the Persian text. **It is switched off right now:** the call answers `503` with code `FEATURE_DISABLED`, and nothing is held or charged. Do not retry in a loop; check again after a day. The edits cannot be applied to the PDF or DOCX through the API.

When it is on, the answer has:

| Field | Type | Meaning |
|---|---|---|
| `edits.vocabulary[]` | array | `find`, `replace`, `scope` (`all`), `category` (`terminology`, `spelling`, `style`, `transliteration`), `reason` |
| `edits.substitutions[]` | array | `sequenceNumber` (paragraph), `find`, `replace`, `category` (`grammar`, `style`, `clarity`, `punctuation`, `word_choice`, `flow`), `reason` |
| `edits.paragraphs[]` | array | `sequenceNumber`, `newText`, `category` (`restructure`, `retranslation`, `coherence`), `reason` |
| `summary` | object | `categories[]`, `totalEdits`, `description` |
| `processedAt`, `faraCost`, `billing`, `saved` | | as for the other tools |

`sequenceNumber` matches `paragraphs[].sequenceNumber` from `GET /api/v1/translate/{jobId}/bilingual`.

- `GET /api/v1/translate/{jobId}/proofread` → `saved: false`, `edits: null` when none; otherwise `hasProofreading: true`, `edits`, `summary`, `processedAt`, `savedAt`, `appliedAt`, `saved: true`.
- `DELETE /api/v1/translate/{jobId}/proofread` → `{"jobId": "…", "deleted": true, "message": "Proofreading results deleted"}`.

## Podcast and audiobook

A spoken Persian podcast or audiobook of the translation is a background job with its own price, review step and webhooks. Create it with `POST /api/v1/audio/jobs` (`{"jobId": "<translation jobId>", "feature": "podcast"}` or `"audiobook"`) — see [Podcast and audiobook](https://faraatarjomeh.com/api/v1/docs/guides/podcast-audiobook.md).

Once made, it is also reachable from the translation:

- `GET /api/v1/translate/{jobId}/podcast` / `GET /api/v1/translate/{jobId}/audiobook` → `hasPodcast` / `hasAudiobook`; when made: `title`, `text`, `audioFileId`, `audioDownloadPath`, `audioContentType`, `audioExtension`, `processedAt`, `savedAt`.
- Download with `GET /api/v1/translate/download/{jobId}/{type}`, `type` = `podcast-audio` or `audiobook-audio` (`audio/mpeg` or `audio/wav`, as in `audioContentType`).
- `DELETE /api/v1/translate/{jobId}/podcast` / `DELETE /api/v1/translate/{jobId}/audiobook` remove the saved result.

## State machine

The tools have no background job. Each saved result is in one of two states:

| state | how you see it | next action for the client |
|---|---|---|
| none | `GET` answers `hasSlides` / `hasMindmap` / `hasSummary` `false`, or `saved: false` | POST to make it (paid tools: after the user agreed to pay) |
| saved | `GET` answers `true` and the content | read it; POST again only to replace it (charges again); DELETE to remove it |

What the translation job must be:

| translation `status` | Make (POST) | Read / delete |
|---|---|---|
| `completed`, `completed_partial` | yes | yes |
| any other | `400` | yes (usually empty) |

## Errors and recovery

Every error is `application/problem+json`; branch on `code` ([error catalog](https://faraatarjomeh.com/api/v1/docs/errors.md)). Every `4xx` and `503` answer is **not** stored under your `Idempotency-Key`: fix the cause (or top up, or wait) and resend with the same key. Success answers and `500`, `502`, `504` **are** stored: the same key replays them, so after a `5xx` other than `503` check whether a result was saved, then use a new key.

| HTTP | code | when | retry? | what the client should do |
|---|---|---|---|---|
| 400 | `BAD_REQUEST` | translation not finished, or too little Persian text | no | Wait for `completed` / `completed_partial`; a document with too little text cannot use the tool. |
| 400 | `INVALID_MAX_FARA` | `maxFara` is not a number of 0 or more (price-first switch on) | no | Send a number of 0 or more, or leave `maxFara` out. |
| 402 | `INSUFFICIENT_CREDITS` | balance below the hold; body has `balance`, `estimatedCost` | no | Stop. Tell the user to top up at https://faraatarjomeh.com. Then POST again (the same key is fine: a 402 is not stored). |
| 403 | `FORBIDDEN`, `INSUFFICIENT_SCOPE` | not your job, or key lacks `write` | no | Check the job id and the key. |
| 404 | `NOT_FOUND` | unknown job; no saved result for a file export; no summary | no | Make the result first, or check the id. |
| 404 | `FEATURE_DISABLED` | the price call while price-first is off | no | Use the normal flow (no `maxFara`). |
| 409 | `PRICE_CHANGED` | the price is above the `maxFara` sent (price-first switch on) | yes, after the user agrees | Show `faraCharged` to the user; if they agree, resend with the same key and a `maxFara` at or above it. |
| 409 | `IDEMPOTENCY_KEY_IN_USE` | the first call with this key still runs | yes | Wait `Retry-After`, resend with the same key. |
| 409 | `IDEMPOTENCY_KEY_ALREADY_USED` | the first answer cannot be replayed (a file, or larger than 256 KB) | no | If `originalStatus` is `200`, read the result with `GET`. |
| 422 | `IDEMPOTENCY_KEY_REUSED` | the key was used for another request | no | Use a new key per action. |
| 429 | `RATE_LIMITED` | 120 requests/min per key | yes | Wait `Retry-After`, resend with the same key. |
| 500 | `INTERNAL_ERROR` | server error | once | `GET` the tool; if nothing was saved, POST again with a **new** key after 1 minute. |
| 502 | `UPSTREAM_ERROR` | the result came back empty | once | POST again with a **new** key after 1 minute. |
| 503 | `FEATURE_DISABLED` | proofreading is switched off | no (today) | Tell the user it is not available. Check again after a day. |
| 503 | `SERVICE_UNAVAILABLE` | the tool is not available right now | yes | Back off (1, 2, 5, 10 min), resend with the same key. |
| 504 | `UPSTREAM_TIMEOUT` | making the result took too long | once | `GET` the tool; if nothing was saved, POST with a **new** key. If it happens twice, stop and tell the user. |

## Rules for agents

- Read before you make: call the tool's `GET` first. If a result is saved, use it; do not pay for a new one unless the user asked.
- While the price-first switch is on, read the price first with `GET /api/v1/translate/{jobId}/tools/price` for slides, mind map and LinkedIn posts. Tell the user the price, get approval, then POST with `maxFara` set to the approved amount. Report `faraCost` after. For proofreading and the other tools, tell the user the tool costs Fara, get approval, and report `faraCost` after.
- Send a new `Idempotency-Key` with every tool POST and reuse it on every resend of that POST.
- Use a client timeout of 30 minutes for tool POSTs. After a timeout, resend with the same key; never send a fresh POST just because the first one was slow.
- Do not call proofreading while it answers `FEATURE_DISABLED`.
- File exports (`slides/generate-files`, `mindmap/pdf`, `summary/pdf`) and downloads are free: repeat them as needed.
- Branch on `code`, never on `detail`.

## Complete script

Both scripts read the free summary, make slides once (reusing saved slides if they exist), build the files, and download the PPTX and the slide PDF. The slides POST resends with the same `Idempotency-Key` after network errors and on `409 IDEMPOTENCY_KEY_IN_USE`, `429` and `503`.

Python 3.9+ (`pip install requests`). Run: `python fara_slides.py 3f1c2b7e-9a4d-4c1e-8f7a-2b9c4d5e6f70 neo`

```python
# fara_slides.py
import os
import sys
import time
import uuid

import requests

BASE_URL = "https://faraatarjomeh.com"
API_KEY = os.environ["FARA_API_KEY"]


def api(method, path, key=None, json_body=None, stream=False, read_timeout=1800):
    headers = {"Authorization": f"Bearer {API_KEY}"}
    if key:
        headers["Idempotency-Key"] = key
    for attempt in range(1, 61):
        try:
            res = requests.request(method, BASE_URL + path, headers=headers, json=json_body,
                                   stream=stream, timeout=(10, read_timeout))
        except requests.RequestException:
            time.sleep(min(2 ** attempt, 60))
            continue
        if res.ok:
            return res if stream else res.json()
        try:
            problem = res.json()
        except ValueError:
            problem = {}
        if res.status_code in (429, 503) and problem.get("code") != "FEATURE_DISABLED" \
                or problem.get("code") == "IDEMPOTENCY_KEY_IN_USE":
            time.sleep(max(int(res.headers.get("Retry-After") or 0), 10))
            continue
        raise RuntimeError(f"{method} {path} -> {res.status_code} {problem.get('code')}: {problem.get('detail')}")
    raise RuntimeError(f"{method} {path}: gave up after retries")


def save(path, filename):
    res = api("GET", path, stream=True)
    with open(filename, "wb") as out:
        for block in res.iter_content(chunk_size=1 << 16):
            out.write(block)
    print(f"Saved {filename}")


def main():
    job_id = sys.argv[1]
    style = sys.argv[2] if len(sys.argv) > 2 else "memphis"

    summary = api("GET", f"/api/v1/translate/{job_id}/summary")
    if summary.get("hasSummary"):
        with open(f"{job_id}-summary.md", "w", encoding="utf-8") as out:
            out.write(summary["digest"])
        print("Saved the summary (free)")

    slides = api("GET", f"/api/v1/translate/{job_id}/slides")
    if not slides.get("hasSlides"):
        made = api("POST", f"/api/v1/translate/{job_id}/slides", key=str(uuid.uuid4()))
        print(f"Made {len(made['slides'])} slides for {made['faraCost']} Fara")

    files = api("POST", f"/api/v1/translate/{job_id}/slides/generate-files",
                json_body={"pptxStyle": style, "pdfStyle": style})
    print(f"Files built with styles {files['styles']}")
    save(f"/api/v1/translate/download/{job_id}/slides-pptx", f"{job_id}-slides.pptx")
    save(f"/api/v1/translate/download/{job_id}/slides-pdf", f"{job_id}-slides.pdf")


if __name__ == "__main__":
    main()
```

Node.js 20+ (no packages). Run: `node fara-slides.mjs 3f1c2b7e-9a4d-4c1e-8f7a-2b9c4d5e6f70 neo`

```js
// fara-slides.mjs
import { writeFile } from "node:fs/promises";
import { randomUUID } from "node:crypto";
import { setTimeout as sleep } from "node:timers/promises";

const BASE_URL = "https://faraatarjomeh.com";
const API_KEY = process.env.FARA_API_KEY;
if (!API_KEY) throw new Error("Set FARA_API_KEY");
const [jobId, style = "memphis"] = process.argv.slice(2);
if (!jobId) throw new Error("Usage: node fara-slides.mjs <jobId> [style]");

async function api(method, path, { json, key, raw = false } = {}) {
  const headers = { Authorization: `Bearer ${API_KEY}` };
  if (key) headers["Idempotency-Key"] = key;
  let body;
  if (json !== undefined) {
    headers["Content-Type"] = "application/json";
    body = JSON.stringify(json);
  }
  for (let attempt = 1; attempt <= 60; attempt++) {
    let res;
    try {
      res = await fetch(BASE_URL + path, { method, headers, body });
    } catch {
      await sleep(Math.min(2 ** attempt, 60) * 1000); // network error or timeout: same key
      continue;
    }
    if (res.ok) return raw ? res : res.json();
    const problem = await res.json().catch(() => ({}));
    const busy = (res.status === 429 || res.status === 503) && problem.code !== "FEATURE_DISABLED";
    if (busy || problem.code === "IDEMPOTENCY_KEY_IN_USE") {
      await sleep(Math.max(Number(res.headers.get("retry-after")) || 0, 10) * 1000);
      continue;
    }
    throw new Error(`${method} ${path} -> ${res.status} ${problem.code}: ${problem.detail}`);
  }
  throw new Error(`${method} ${path}: gave up after retries`);
}

async function save(path, filename) {
  const res = await api("GET", path, { raw: true });
  await writeFile(filename, Buffer.from(await res.arrayBuffer()));
  console.log(`Saved ${filename}`);
}

const summary = await api("GET", `/api/v1/translate/${jobId}/summary`);
if (summary.hasSummary) {
  await writeFile(`${jobId}-summary.md`, summary.digest, "utf8");
  console.log("Saved the summary (free)");
}

const slides = await api("GET", `/api/v1/translate/${jobId}/slides`);
if (!slides.hasSlides) {
  const made = await api("POST", `/api/v1/translate/${jobId}/slides`, { key: randomUUID() });
  console.log(`Made ${made.slides.length} slides for ${made.faraCost} Fara`);
}

const files = await api("POST", `/api/v1/translate/${jobId}/slides/generate-files`, {
  json: { pptxStyle: style, pdfStyle: style },
});
console.log(`Files built with styles ${JSON.stringify(files.styles)}`);
await save(`/api/v1/translate/download/${jobId}/slides-pptx`, `${jobId}-slides.pptx`);
await save(`/api/v1/translate/download/${jobId}/slides-pdf`, `${jobId}-slides.pdf`);
```
