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

# Start Optimization

> Start an optimization of a workflow's field descriptions, measured or one-shot

*Rate limit tier: **submission**, 60 requests/min. See [Rate limits](https://docs.anyformat.ai/api-reference-v3/introduction.md#rate-limits).*

Starts an [optimization](https://docs.anyformat.ai/guides/health/optimizer.md): a run that rewrites a workflow's **field descriptions** to extract more accurately. The call is **async and fire-and-forget**. It returns `202` at once with the new optimization. Poll it with [`GET …/optimizations/{optimization_id}/`](https://docs.anyformat.ai/api-reference-v3/optimizations/get) until `status` is `done` or `failed`.

The body is discriminated on `kind`:

| `kind` | What it does | Body fields | Needs |
| - | - | - | - |
| `extraction` | A **measured** run. It scores the current version against the dataset's ground truth, then tries rewrites and keeps only those that raise accuracy. | `max_rounds`, 1 to 10, default 3 | Ground truth in the dataset, else `422 GT_INVALID` |
| `extraction_oneshot` | **One unmeasured round.** It reflects once on the dataset's existing extractions and your hint, then applies its suggestion without checking it. | `user_context`, up to 4000 characters | A dataset extraction or a `user_context`, else `422 ONESHOT_SIGNALS_MISSING` |

A one-shot run reports no accuracy: `baseline_accuracy` and `best_accuracy` stay `null`. Pick it when the dataset has no ground truth yet, or when you want a quick suggestion to review.

## One optimization at a time

A workflow runs **one optimization at a time, of either kind**. A start while another runs returns `409 OPTIMIZATION_ALREADY_RUNNING`. [List the workflow's optimizations](https://docs.anyformat.ai/api-reference-v3/optimizations/list.md) to find the running one. A run whose worker stopped for more than 100 minutes is reported `failed` and no longer blocks.

## Credits

A measured run is billed like evals, one extraction per dataset document for the baseline and for every round. A one-shot run is billed one flat charge when it finishes `done`, even when it changes nothing, and nothing when it fails. For either kind, an organization with no credit gets `402 INSUFFICIENT_CREDIT` and nothing starts.

While a measured run evaluates a round, that round's candidate is the workflow's latest version, so a document run on the workflow at that moment uses it. The run ends by saving the best descriptions as the latest version. See [How credits work](https://docs.anyformat.ai/concepts/how-credits-work.md).

## Idempotency

Without an `Idempotency-Key`, **every call starts a new optimization**. Supplying the header **replays** instead: a retry with the same key and body returns the **original** optimization, with the `status` it had at the first call, and starts no second run. Reusing the key with another body returns `422 IDEMPOTENCY_KEY_REUSED`. See [Idempotency](https://docs.anyformat.ai/api-reference-v3/introduction.md#idempotency).

```bash curl theme={null}
curl -X POST 'https://api.anyformat.ai/v3/workflows/0686bb97-8c30-70f0-8000-97669e000eb8/optimizations/' \
  -H 'Authorization: Bearer YOUR_API_KEY' \
  -H 'Idempotency-Key: optimize-invoices-2026-07-05' \
  -H 'Content-Type: application/json' \
  -d '{"kind": "extraction", "max_rounds": 3}'
```

```python Python (SDK) theme={null}
from anyformat.sdk import Client

client = Client(api_key="YOUR_API_KEY")

workflow_id = "0686bb97-8c30-70f0-8000-97669e000eb8"

# A measured run, scored against the dataset's ground truth.
optimization = client.start_optimization(
    workflow_id, "extraction", max_rounds=3, idempotency_key="optimize-invoices-2026-07-05"
)

# A one-shot run, which needs no ground truth.
one_shot = client.start_optimization(
    workflow_id, "extraction_oneshot", user_context="The total includes VAT."
)
print(optimization.id, optimization.status)
```

```typescript TypeScript theme={null}
import { Anyformat } from '@anyformat/sdk';

const af = new Anyformat({ apiKey: 'YOUR_API_KEY' });

const workflowId = '0686bb97-8c30-70f0-8000-97669e000eb8';

// A measured run, scored against the dataset's ground truth.
const optimization = await af.startOptimization(workflowId, {
  kind: 'extraction',
  maxRounds: 3,
  idempotencyKey: 'optimize-invoices-2026-07-05',
});

// A one-shot run, which needs no ground truth.
const oneShot = await af.startOptimization(workflowId, {
  kind: 'extraction_oneshot',
  userContext: 'The total includes VAT.',
});
console.log(optimization.id, optimization.status);
```

```json Response (202 Accepted) theme={null}
{
  "id": "069dcc2c-e14c-7606-8000-2ee4fb17b4f9",
  "workflow_id": "0686bb97-8c30-70f0-8000-97669e000eb8",
  "kind": "extraction",
  "status": "evaluating",
  "max_rounds": 3,
  "baseline_accuracy": null,
  "best_accuracy": null,
  "result_version_id": null,
  "error": null,
  "rounds": [
    {
      "round_no": 0,
      "version_id": "abcdef1234",
      "matched": 0,
      "mismatched": 0,
      "accuracy": 0.0,
      "accepted": false,
      "note": null,
      "created_at": "2026-07-05T10:00:00Z",
      "per_field": []
    }
  ],
  "created_at": "2026-07-05T10:00:00Z",
  "finished_at": null
}
```


## OpenAPI

````yaml POST /v3/workflows/{workflow_id}/optimizations/
openapi: 3.1.0
info:
  title: anyformat API
  description: >
    Document extraction and workflow automation API.


    AnyFormat lets you define extraction workflows that pull structured data
    from any document — PDFs, images, scanned files, or plain text. Upload a
    file, run it through a workflow, and get back structured fields with
    confidence scores and source evidence.


    ## Quick start


    See the [Quick start
    guide](https://docs.anyformat.ai/api-reference-v3/introduction) for a
    walkthrough.


    ## Authentication


    All endpoints (except `/health/`) require a Bearer token in the
    `Authorization` header:


    ```

    Authorization: Bearer <your-api-key>

    ```


    Get your API key from
    [app.anyformat.ai/api-key](https://app.anyformat.ai/api-key).


    ## Versioning


    Endpoints are versioned by path prefix (`/v3/`). Every response under

    a versioned prefix includes `X-API-Version`.
  version: 3.0.0
servers:
  - url: https://api.anyformat.ai
    description: API server
security: []
tags:
  - name: workflows
    description: >-
      Workflows define extraction templates — what fields to extract from
      documents. Create workflows, upload files, run extractions, and fetch
      results.
  - name: document-packets
    description: >-
      Document packets group uploaded documents for a workflow. Address a packet
      directly to (re-)run its workflow.
  - name: runs
    description: >-
      Extraction runs — the first-class result entity. Each run is a single
      execution of a workflow against a document packet; fetch its status and
      results flat by run id.
  - name: splits
    description: >-
      Splits — the sub-documents a splitter node carves out of a packet.
      Download any one of them as a PDF, built from the source documents on
      request and never stored.
  - name: webhooks
    description: >-
      Webhooks — an HTTPS endpoint of yours that hears of every run's ending,
      signed per the Standard Webhooks specification, instead of polling the
      run.
  - name: parse
    description: >-
      Parse a single document with the platform's fast lite parse — a one-call
      shortcut over the workflow upload + run primitives, backed by your
      organization's system parse workflow.
  - name: health
    description: Health check endpoints to verify API availability.
paths:
  /v3/workflows/{workflow_id}/optimizations/:
    post:
      tags:
        - optimizations
      summary: Start an optimization
      description: >-
        Start an optimization of a workflow's field descriptions (async,
        fire-and-forget).


        `kind: "extraction"` is a measured run. It scores the workflow against
        the dataset's

        ground truth, then tries up to `max_rounds` rewrites and keeps those
        that raise accuracy.

        It needs ground truth in the dataset, else `422 GT_INVALID`.


        `kind: "extraction_oneshot"` is a single unmeasured round. It reflects
        once on the

        dataset's existing extractions and the optional `user_context`, then
        applies its suggestion

        without checking it. It needs one of the two, else `422
        ONESHOT_SIGNALS_MISSING`.


        Both return `202` with the new optimization; poll `GET
        …/optimizations/{optimization_id}/`

        until `status` is `done` or `failed`. One optimization runs per workflow
        at a time: a second

        start while one runs returns `409 OPTIMIZATION_ALREADY_RUNNING`.


        Without an `Idempotency-Key` every call starts a NEW optimization.
        Supplying the header

        replays: a retry with the same key and body returns the original
        optimization, with its status

        as of the first call, instead of starting another.
      operationId: v3_start_optimization
      parameters:
        - name: workflow_id
          in: path
          required: true
          schema:
            type: string
            title: Workflow Id
        - name: Idempotency-Key
          in: header
          required: false
          schema:
            anyOf:
              - type: string
              - type: 'null'
            description: >-
              Optional caller-supplied key (Stripe convention). Retrying with
              the same key returns the original optimization instead of starting
              (and billing) a second one.
            title: Idempotency-Key
          description: >-
            Optional caller-supplied key (Stripe convention). Retrying with the
            same key returns the original optimization instead of starting (and
            billing) a second one.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/OptimizationStartRequest'
      responses:
        '202':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/OptimizationV3'
          headers:
            Idempotent-Replayed:
              description: >-
                `true` when this response replays an earlier request sent with
                the same `Idempotency-Key`; absent on a first request.
              schema:
                type: string
                enum:
                  - 'true'
            X-RateLimit-Limit:
              description: Requests allowed per window (60s).
              schema:
                type: integer
            X-RateLimit-Remaining:
              description: Requests remaining in the current window.
              schema:
                type: integer
            X-RateLimit-Reset:
              description: Seconds until the current window resets.
              schema:
                type: integer
        '400':
          description: >-
            `OPERATOR_DEPRECATED` — This workflow version uses a deprecated
            operator and cannot run.

            `VALIDATION_ERROR` — The request failed validation. `detail` is a
            list of `{type, loc, msg}`, one per failure; `loc[0]` is the request
            part.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorEnvelope'
              examples:
                VALIDATION_ERROR:
                  value:
                    error: The request failed validation.
                    detail:
                      - type: missing
                        loc:
                          - body
                          - name
                        msg: Field required
                    error_code: VALIDATION_ERROR
                    retryable: false
                    request_id: req_abc123
                    recovery: >-
                      Read `detail` for what failed validation, correct the
                      request, and send it again.
                OPERATOR_DEPRECATED:
                  value:
                    error: >-
                      This workflow version uses a deprecated operator and
                      cannot run.
                    detail: >-
                      This workflow version uses a deprecated operator and
                      cannot run.
                    error_code: OPERATOR_DEPRECATED
                    retryable: false
                    request_id: req_abc123
                    recovery: >-
                      Replace the operator on the nodes in `params.node_ids`,
                      save a new version, and run again.
        '401':
          description: >-
            Authentication failed — the API key is not valid (`INVALID_API_KEY`)
            or the request carries none (`MISSING_API_KEY`).
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorEnvelope'
              examples:
                INVALID_API_KEY:
                  value:
                    error: The API key is not valid.
                    detail: The API key is not valid.
                    error_code: INVALID_API_KEY
                    retryable: false
                    request_id: req_abc123
                    recovery: >-
                      Check that the key is complete and has not been revoked,
                      or create a new key.
                MISSING_API_KEY:
                  value:
                    error: The request carries no API key.
                    detail: The request carries no API key.
                    error_code: MISSING_API_KEY
                    retryable: false
                    request_id: req_abc123
                    recovery: >-
                      Send your API key in the `Authorization: Bearer <key>`
                      header.
        '402':
          description: >-
            `INSUFFICIENT_CREDIT` — The organization has no extraction credit
            left.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorEnvelope'
              examples:
                INSUFFICIENT_CREDIT:
                  value:
                    error: The organization has no extraction credit left.
                    detail: The organization has no extraction credit left.
                    error_code: INSUFFICIENT_CREDIT
                    retryable: false
                    request_id: req_abc123
                    recovery: >-
                      Top up the organization's credit or upgrade its plan, then
                      run again.
        '403':
          description: >-
            Access denied — the API key lacks access to this resource or the
            scope this call needs (`ACCESS_DENIED`,
            `insufficient_api_key_scope`).
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorEnvelope'
              examples:
                ACCESS_DENIED:
                  value:
                    error: You do not have access to this resource.
                    detail: You do not have access to this resource.
                    error_code: ACCESS_DENIED
                    retryable: false
                    request_id: req_abc123
                    recovery: >-
                      Use an API key from the organization that owns this
                      resource, or ask one of its admins for access.
                insufficient_api_key_scope:
                  value:
                    error: The API key does not carry the scope this call needs.
                    detail: The API key does not carry the scope this call needs.
                    error_code: insufficient_api_key_scope
                    retryable: false
                    request_id: req_abc123
                    recovery: >-
                      Create an API key with the scope `params.required_scope`
                      names, and use it for this call.
        '404':
          description: >-
            Resource not found — the workflow, document packet, or run ID does
            not exist or is not visible to this API key.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorEnvelope'
              examples:
                NOT_FOUND:
                  value:
                    error: The resource does not exist.
                    detail: The resource does not exist.
                    error_code: NOT_FOUND
                    retryable: false
                    request_id: req_abc123
                    recovery: >-
                      Check the ID, and that it belongs to your API key's
                      organization; `params.resource_type` names what is
                      missing.
        '409':
          description: >-
            `OPTIMIZATION_ALREADY_RUNNING` — An optimization is already running
            for this workflow.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorEnvelope'
              examples:
                OPTIMIZATION_ALREADY_RUNNING:
                  value:
                    error: An optimization is already running for this workflow.
                    detail: An optimization is already running for this workflow.
                    error_code: OPTIMIZATION_ALREADY_RUNNING
                    retryable: true
                    request_id: req_abc123
                    recovery: >-
                      Wait for the running optimization to finish, then start a
                      new one; list the workflow's optimizations to see it.
        '422':
          description: >-
            `GT_INVALID` — The ground truth is not valid.

            `ONESHOT_SIGNALS_MISSING` — The one-shot optimization has nothing to
            learn from.

            `EXTRACT_NODE_UNRESOLVED` — The request does not say which extract
            node to use.

            `IDEMPOTENCY_KEY_REUSED` — The idempotency key was already used with
            a different request.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorEnvelope'
              examples:
                GT_INVALID:
                  value:
                    error: The ground truth is not valid.
                    detail: The ground truth is not valid.
                    error_code: GT_INVALID
                    retryable: false
                    request_id: req_abc123
                    recovery: >-
                      Correct the ground truth against `detail` so it matches
                      the workflow's fields, and upload it again.
                ONESHOT_SIGNALS_MISSING:
                  value:
                    error: The one-shot optimization has nothing to learn from.
                    detail: The one-shot optimization has nothing to learn from.
                    error_code: ONESHOT_SIGNALS_MISSING
                    retryable: false
                    request_id: req_abc123
                    recovery: >-
                      Run documents through the workflow's dataset first, or
                      send a `user_context` that describes what the extraction
                      gets wrong, then start it again.
                EXTRACT_NODE_UNRESOLVED:
                  value:
                    error: The request does not say which extract node to use.
                    detail: The request does not say which extract node to use.
                    error_code: EXTRACT_NODE_UNRESOLVED
                    retryable: false
                    request_id: req_abc123
                    recovery: >-
                      Name in the request the extract node the ground truth
                      belongs to.
                IDEMPOTENCY_KEY_REUSED:
                  value:
                    error: >-
                      The idempotency key was already used with a different
                      request.
                    detail: >-
                      The idempotency key was already used with a different
                      request.
                    error_code: IDEMPOTENCY_KEY_REUSED
                    retryable: false
                    request_id: req_abc123
                    recovery: >-
                      Resend the original request unchanged to get its result,
                      or read the resource it created from `params.resource_id`;
                      use a new `Idempotency-Key` only for a genuinely new
                      request.
        '429':
          description: >-
            Rate limited — retry after the `Retry-After` header. Default
            windows: 60 requests/minute for extraction submission, 600
            requests/minute for general endpoints.
          headers:
            Retry-After:
              description: Seconds until the next request is allowed.
              schema:
                type: integer
            X-RateLimit-Limit:
              description: Requests allowed per window (60s).
              schema:
                type: integer
            X-RateLimit-Remaining:
              description: Requests remaining in the current window.
              schema:
                type: integer
            X-RateLimit-Reset:
              description: Seconds until the current window resets.
              schema:
                type: integer
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorEnvelope'
              examples:
                RATE_LIMITED:
                  value:
                    error: Too many requests.
                    detail: Too many requests.
                    error_code: RATE_LIMITED
                    retryable: true
                    request_id: req_abc123
                    recovery: >-
                      Wait the seconds the `Retry-After` header gives, or back
                      off exponentially without one, then retry.
        '500':
          description: >-
            An internal error stopped the request — `retryable=true`. Retry with
            backoff.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorEnvelope'
              examples:
                INTERNAL_ERROR:
                  value:
                    error: An internal error stopped the request.
                    detail: An internal error stopped the request.
                    error_code: INTERNAL_ERROR
                    retryable: true
                    request_id: req_abc123
                    recovery: >-
                      Retry with exponential backoff, and contact support with
                      the `request_id` if it keeps failing.
        '502':
          description: >-
            A backend service broke the connection before it answered, or
            failed. Retry with backoff when `retryable` is true.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorEnvelope'
              examples:
                INTERNAL_ERROR:
                  value:
                    error: An internal error stopped the request.
                    detail: An internal error stopped the request.
                    error_code: INTERNAL_ERROR
                    retryable: true
                    request_id: req_abc123
                    recovery: >-
                      Retry with exponential backoff, and contact support with
                      the `request_id` if it keeps failing.
        '503':
          description: >-
            A backend service could not be reached or is unavailable
            (`SERVICE_UNAVAILABLE`). Retry with backoff when `retryable` is
            true.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorEnvelope'
              examples:
                SERVICE_UNAVAILABLE:
                  value:
                    error: The service is temporarily unavailable.
                    detail: The service is temporarily unavailable.
                    error_code: SERVICE_UNAVAILABLE
                    retryable: true
                    request_id: req_abc123
                    recovery: Retry the request with exponential backoff.
        '504':
          description: >-
            A backend service did not answer in time. Retry with backoff when
            `retryable` is true.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorEnvelope'
              examples:
                GATEWAY_TIMEOUT:
                  value:
                    error: The upstream service did not answer in time.
                    detail: The upstream service did not answer in time.
                    error_code: GATEWAY_TIMEOUT
                    retryable: true
                    request_id: req_abc123
                    recovery: Retry the request with exponential backoff.
      security:
        - ApiKeyAuth: []
components:
  schemas:
    OptimizationStartRequest:
      oneOf:
        - $ref: '#/components/schemas/ExtractionOptimizationRequest'
        - $ref: '#/components/schemas/OneshotOptimizationRequest'
      title: OptimizationStartRequest
      description: >-
        Body for `POST /v3/workflows/{workflow_id}/optimizations/`,
        discriminated on `kind`.
      discriminator:
        propertyName: kind
        mapping:
          extraction: '#/components/schemas/ExtractionOptimizationRequest'
          extraction_oneshot: '#/components/schemas/OneshotOptimizationRequest'
    OptimizationV3:
      properties:
        id:
          type: string
          title: Id
          description: Unique identifier of the optimization (hyphenated UUID).
          examples:
            - 069dcc2c-e14c-7606-8000-2ee4fb17b4f9
        workflow_id:
          type: string
          title: Workflow Id
          description: The optimized workflow (hyphenated UUID).
        kind:
          $ref: '#/components/schemas/OptimizationKind'
        status:
          $ref: '#/components/schemas/OptimizationStatus'
        max_rounds:
          type: integer
          title: Max Rounds
          description: Most rounds the run may try.
        baseline_accuracy:
          anyOf:
            - type: number
            - type: 'null'
          title: Baseline Accuracy
          description: >-
            Accuracy before any change; `null` until scored and on a one-shot
            run.
        best_accuracy:
          anyOf:
            - type: number
            - type: 'null'
          title: Best Accuracy
          description: >-
            Best accuracy any round reached; `null` until scored and on a
            one-shot run.
        result_version_id:
          anyOf:
            - type: string
            - type: 'null'
          title: Result Version Id
          description: >-
            The workflow version that holds the optimized descriptions; `null`
            until a round is kept.
        error:
          anyOf:
            - type: string
            - type: 'null'
          title: Error
          description: Why the run failed; `null` unless `status` is `failed`.
        rounds:
          items:
            $ref: '#/components/schemas/OptimizationRoundV3'
          type: array
          title: Rounds
        created_at:
          anyOf:
            - type: string
              format: date-time
            - type: 'null'
          title: Created At
          description: When the run started (ISO 8601).
        finished_at:
          anyOf:
            - type: string
              format: date-time
            - type: 'null'
          title: Finished At
          description: >-
            When the run reached `done` or `failed` (ISO 8601); `null` while it
            runs.
      type: object
      required:
        - id
        - workflow_id
        - kind
        - status
        - max_rounds
        - rounds
      title: OptimizationV3
      description: One optimization run.
    ErrorEnvelope:
      type: object
      title: ErrorEnvelope
      description: >-
        Uniform error response. `retryable=true` means the same request may
        succeed on retry (with backoff); `retryable=false` means the caller must
        change the request before retrying.
      required:
        - error
        - error_code
        - retryable
        - request_id
      properties:
        error:
          type: string
          description: Short human-readable summary.
        detail:
          description: >-
            Machine-readable detail, any JSON value. A string for most errors, a
            list of `{type, loc, msg}` objects for `VALIDATION_ERROR`, whose
            `loc` starts with `body`, `query`, `path`, `header`, `form` or
            `tool`, and an object for a structured error such as
            `FILENAME_CONFLICT` (`detail.conflicts`).
        error_code:
          type: string
          enum:
            - ACCESS_DENIED
            - AUTH_FAILED
            - CONCURRENT_EDIT
            - CONFLICT
            - DATASET_DOCUMENT_REJECTED
            - DATASET_GROUND_TRUTH_SAVE_FAILED
            - DATASET_INVALID_REQUEST
            - DATASET_UNSUPPORTED
            - EMPTY_EVAL
            - ENDPOINT_RETIRED
            - EXTRACT_MODE_FORBIDDEN
            - EXTRACT_NODE_UNRESOLVED
            - FILENAME_CONFLICT
            - FILE_TOO_LARGE
            - GATEWAY_TIMEOUT
            - GONE
            - GRAPH_READBACK_FAILED
            - GT_INVALID
            - IDEMPOTENCY_KEY_REUSED
            - IMMUTABLE_WORKFLOW
            - INSUFFICIENT_CREDIT
            - INTERNAL_ERROR
            - INTERNAL_INCONSISTENCY
            - INVALID_API_KEY
            - INVALID_JSON
            - INVALID_LOOKUP_FILE_ENCODING
            - INVALID_VALUE
            - INVALID_WORKFLOW_CONFIG
            - KNOWLEDGE_NOT_ENABLED
            - KNOWLEDGE_NOT_READY
            - KNOWLEDGE_THREAD_MISMATCH
            - KNOWLEDGE_UNSUPPORTED_SNAPSHOT_FORMAT
            - LOOKUP_FIELD_WITHOUT_FILE
            - METHOD_NOT_ALLOWED
            - MISSING_API_KEY
            - MULTIFILE_UNSUPPORTED
            - NOT_ACCEPTABLE
            - NOT_ASSIGNED_VERIFIER
            - NOT_FOUND
            - NOT_IMPLEMENTED
            - NOT_IN_DATASET
            - OBJECT_STORAGE_UNAVAILABLE
            - ONESHOT_SIGNALS_MISSING
            - OPERATOR_DEPRECATED
            - OPERATOR_NOT_AVAILABLE
            - OPTIMIZATION_ALREADY_RUNNING
            - PARSE_MODE_FORBIDDEN
            - PAYMENT_REQUIRED
            - PRECONDITION_FAILED
            - RATE_LIMITED
            - REPARSE_REQUIRED
            - REQUEST_REJECTED
            - REQUEST_TOO_LARGE
            - RUN_IN_PROGRESS
            - SERVICE_UNAVAILABLE
            - SPLIT_HAS_NO_PAGES
            - SPLIT_SOURCE_NOT_PDF
            - TOPOLOGY_INVALID
            - UNSUPPORTED_FILE_TYPE
            - UNSUPPORTED_LOOKUP_FILE
            - UNSUPPORTED_MEDIA_TYPE
            - UPLOAD_SNIFF_BUDGET_EXCEEDED
            - URL_UNREACHABLE
            - VALIDATION_ERROR
            - WEBHOOK_SUBSCRIPTION_LIMIT
            - WORKFLOW_CONCURRENT_EDIT
            - WORKFLOW_NAME_CONFLICT
            - ZERO_DATA_RETENTION_REFUSES_DATASET
            - ZERO_DATA_RETENTION_REFUSES_KNOWLEDGE
            - deprecated_operator_ack_required
            - insufficient_api_key_scope
            - terms_acceptance_required
          description: >-
            Stable identifier for programmatic handling. New values can be added
            at any time, so a client must accept a code it does not know.
          examples:
            - VALIDATION_ERROR
            - AUTH_FAILED
            - NOT_FOUND
            - PRECONDITION_FAILED
            - RATE_LIMITED
            - INTERNAL_ERROR
            - GATEWAY_TIMEOUT
        retryable:
          type: boolean
          description: True when the caller should retry (with backoff for 429/412/5xx).
        request_id:
          type: string
          description: Correlates this response with server logs.
        params:
          type: object
          additionalProperties: true
          description: >-
            Values specific to this occurrence of the error that a caller needs
            to recover, such as `node_ids` or `required_scope`, keyed by name.
            Absent when the code relays none.
        doc_url:
          type: string
          format: uri
          description: Link to the documentation of this `error_code`.
        recovery:
          type: string
          description: >-
            One sentence that says what to do next. Absent when the `error_code`
            has none, or when `retryable` differs from the code's usual value.
    ExtractionOptimizationRequest:
      properties:
        kind:
          type: string
          const: extraction
          title: Kind
          description: >-
            A measured run: every round is scored against the dataset's ground
            truth.
        max_rounds:
          type: integer
          maximum: 10
          minimum: 1
          title: Max Rounds
          description: >-
            Most rounds the run may try. It stops earlier when rounds stop
            improving accuracy.
          default: 3
      additionalProperties: false
      type: object
      required:
        - kind
      title: ExtractionOptimizationRequest
    OneshotOptimizationRequest:
      properties:
        kind:
          type: string
          const: extraction_oneshot
          title: Kind
          description: A single unmeasured round that needs no ground truth.
        user_context:
          type: string
          maxLength: 4000
          title: User Context
          description: >-
            Free text on what the extraction gets wrong. Required when the
            dataset holds no extraction to learn from.
          default: ''
      additionalProperties: false
      type: object
      required:
        - kind
      title: OneshotOptimizationRequest
    OptimizationKind:
      type: string
      enum:
        - extraction
        - extraction_oneshot
      title: OptimizationKind
    OptimizationStatus:
      type: string
      enum:
        - evaluating
        - proposing
        - done
        - failed
      title: OptimizationStatus
      description: >-
        Lifecycle of a run. Non-terminal: `evaluating`, `proposing`. Terminal:
        `done`, `failed`.
    OptimizationRoundV3:
      properties:
        round_no:
          type: integer
          title: Round No
          description: 0 is the baseline; rounds that propose a change count from 1.
        version_id:
          anyOf:
            - type: string
            - type: 'null'
          title: Version Id
          description: Workflow version the round scored; `null` before it is minted.
        matched:
          type: integer
          title: Matched
          description: Values that matched ground truth.
        mismatched:
          type: integer
          title: Mismatched
          description: Values that did not match ground truth.
        accuracy:
          type: number
          title: Accuracy
          description: Round accuracy in [0, 1].
        accepted:
          type: boolean
          title: Accepted
          description: Whether the round's change was kept.
        note:
          anyOf:
            - type: string
            - type: 'null'
          title: Note
          description: Why the round was kept or dropped.
        created_at:
          anyOf:
            - type: string
              format: date-time
            - type: 'null'
          title: Created At
          description: When the round was recorded (ISO 8601).
        per_field:
          items:
            $ref: '#/components/schemas/OptimizationFieldScoreV3'
          type: array
          title: Per Field
          description: >-
            Scores per field. Empty on a list item: read the optimization by id
            for them.
      type: object
      required:
        - round_no
        - matched
        - mismatched
        - accuracy
        - accepted
        - per_field
      title: OptimizationRoundV3
    OptimizationFieldScoreV3:
      properties:
        persistent_id:
          type: string
          title: Persistent Id
          description: The field's `persistent_id` in the workflow schema.
        name:
          anyOf:
            - type: string
            - type: 'null'
          title: Name
          description: The field's name in the round's version.
        matched:
          type: integer
          title: Matched
          description: Values of this field that matched ground truth.
        mismatched:
          type: integer
          title: Mismatched
          description: Values of this field that did not match ground truth.
        accuracy:
          type: number
          title: Accuracy
          description: '`matched / (matched + mismatched)`, 0 when nothing was graded.'
      type: object
      required:
        - persistent_id
        - matched
        - mismatched
        - accuracy
      title: OptimizationFieldScoreV3
  securitySchemes:
    ApiKeyAuth:
      type: http
      description: >-
        API key issued from app.anyformat.ai/api-key. Send as `Authorization:
        Bearer <key>`.
      scheme: bearer

````

This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.