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

> ## Agent Instructions
> Start with /introduction/getting-started. Use the Direct Query API (POST /query) with the Newton Fusion model (text, image, and video reasoning) or the Newton Omega encoder (time-series embeddings). ATAI_API_ENDPOINT must include the version path: /v0.5 for most APIs, /v0.6 for the Fine-Tuning Service. Pages whose descriptions are marked (Archived) document the legacy Lens runtime — do not use them for new projects.

# Cancel Optimization

> Cancel a pending or running optimization run

<Callout icon="clock" color="#3064E3" iconType="solid">
  Requires [version 1.1.12](/release-notes/1.1.x#v1-1-12) or later of the Archetype platform.
</Callout>

## Overview

This endpoint cancels a pending or running optimization and returns it in its `cancelled` state.
It also cancels any non-terminal trials, so the trial list does not leave a stale row behind.
Trials that had already completed keep their results and stay counted in `progress.completed`.

A run that is already terminal — that is, one whose `status` is one of `completed`, `failed`, or
`cancelled` — has nothing to cancel and returns HTTP status code `409`.

<Note>
  One use case for this endpoint is to cancel a running optimization prior to deleting it using
  [Delete Optimization](/api-reference/agents/optimizations/delete-optimization), since deleting
  an optimization will fail with a `409` HTTP status code if its state is non-terminal.
</Note>

## Request

<ParamField path="optimization_id" type="string" required>
  Optimization `opt_` id.
</ParamField>

## Response

Returns the cancelled run, in the same format returned by
[Get Optimization](/api-reference/agents/optimizations/get-optimization).

<ResponseField name="id" type="string" required>
  TypeID-encoded optimization identifier (`opt_` prefix).
</ResponseField>

<ResponseField name="name" type="string" required>
  Human label for the run.
</ResponseField>

<ResponseField name="org_id" type="string" required>
  Organization identifier the run belongs to.
</ResponseField>

<ResponseField name="blueprint_id" type="string" required>
  The blueprint being searched.
</ResponseField>

<ResponseField name="objective" type="string" required>
  The primary metric name that was being maximized.
</ResponseField>

<ResponseField name="search_space" type="object" required>
  The parameter space the run sampled from.
</ResponseField>

<ResponseField name="budget" type="object" required>
  The run's budget knobs — `max_trials`.
</ResponseField>

<ResponseField name="validation_examples" type="array" required>
  The scoring examples as resolved.
</ResponseField>

<ResponseField name="status" type="string" required>
  Optimization lifecycle status; `cancelled` after a successful cancel.
</ResponseField>

<ResponseField name="progress" type="object" required>
  Per-status trial counts. Trials that were still pending or running move to `cancelled`.
</ResponseField>

<ResponseField name="created_by" type="string" required>
  Subject id (`usr_...` or `key_...`) that created this run.
</ResponseField>

<ResponseField name="created_at" type="string" required>
  Creation timestamp (date-time).
</ResponseField>

<ResponseField name="best_trial_id" type="string">
  The trial the run picked as its winner. Set by the promotion step on successful completion, so
  it is `null` on a cancelled run.
</ResponseField>

<ResponseField name="started_at" type="string">
  When the run started; `null` if it never did.
</ResponseField>

<ResponseField name="completed_at" type="string">
  When the run finished; `null` while unfinished.
</ResponseField>

<ResponseField name="error" type="string">
  Failure detail; `null` unless the run failed.
</ResponseField>

<RequestExample>
  ```bash cURL theme={"system"}
  curl -X POST "$ATAI_API_URL/agents/optimizations/opt_01jcb1m3t7v5xq8nr2h6kdzs4w/cancel" \
    -H "Authorization: Bearer $ATAI_API_KEY"
  ```

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

  base_url = os.environ["ATAI_API_URL"]
  api_key = os.environ["ATAI_API_KEY"]

  response = requests.post(
      f"{base_url}/agents/optimizations/opt_01jcb1m3t7v5xq8nr2h6kdzs4w/cancel",
      headers={"Authorization": f"Bearer {api_key}"},
  )

  if response.status_code == 200:
      run = response.json()
      print(f"{run['id']} is now {run['status']}")
  elif response.status_code == 409:
      print("Optimization already terminal")
  else:
      print(f"Error: {response.json()['errors']}")
  ```

  ```javascript JavaScript theme={"system"}
  const response = await fetch(
    `${process.env.ATAI_API_URL}/agents/optimizations/opt_01jcb1m3t7v5xq8nr2h6kdzs4w/cancel`,
    {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${process.env.ATAI_API_KEY}`
      }
    }
  );

  const body = await response.json();

  if (response.ok) {
    console.log(`${body.id} is now ${body.status}`);
  } else if (response.status === 409) {
    console.error('Optimization already terminal');
  } else {
    console.error('Error:', body.errors);
  }
  ```
</RequestExample>

<ResponseExample>
  ```json 200 - Optimization cancelled theme={"system"}
  {
    "id": "opt_01jcb1m3t7v5xq8nr2h6kdzs4w",
    "name": "Window size sweep",
    "org_id": "org_01jc8m5r2vq9xt4bn7h3kdzs6w",
    "blueprint_id": "blp_01jc9n7k3xf8mbq2v5t0ary6de",
    "objective": "macro_f1",
    "search_space": {
      "parameters": {
        "window_size": {
          "kind": "value",
          "spec": {"type": "categorical", "values": [512, 1024, 2048]}
        }
      }
    },
    "budget": {"max_trials": 24},
    "constraints": null,
    "training_examples": null,
    "calibration_examples": null,
    "validation_examples": [
      {
        "name": "file_def456",
        "ordinal": 1,
        "inputs": [
          {"type": "file", "id": "file_def456", "format": "csv", "crc32c": "AAAAAA=="}
        ]
      }
    ],
    "status": "cancelled",
    "progress": {
      "pending": 0,
      "running": 0,
      "completed": 12,
      "failed": 0,
      "cancelled": 12,
      "infeasible": 2
    },
    "best_trial_id": null,
    "created_by": "usr_01jc8m4p3rt6vx9qn2h5kdzb7y",
    "created_at": "2026-09-18T12:02:44Z",
    "started_at": "2026-09-18T12:02:51Z",
    "completed_at": null,
    "error": null
  }
  ```

  ```json 404 - Optimization not found theme={"system"}
  {
    "errors": [
      {
        "code": "<error_code>",
        "message": "Optimization not found.",
        "suggestion": null,
        "error_uid": "err-xxxxxxxx"
      }
    ]
  }
  ```

  ```json 409 - Optimization already terminal theme={"system"}
  {
    "errors": [
      {
        "code": "<error_code>",
        "message": "Optimization already terminal.",
        "suggestion": null,
        "error_uid": "err-xxxxxxxx"
      }
    ]
  }
  ```
</ResponseExample>


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