> ## 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.

# Create Optimization

> Start a hyperparameter search over a blueprint

<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 creates and starts an optimization run over a blueprint.

It returns immediately with the run's ID and a `pending` status. The platform drives it to
`completed`, `failed`, or `cancelled` through its controller; poll
[Get Optimization](/api-reference/agents/optimizations/get-optimization) to observe progress and
the winning trial.

A run samples points from `search_space`, fits and scores a trial at each one, and maximizes
`objective` — a metric name the blueprint's metrics schema declares. Every trial's eval scores
against `validation_examples`. Trials that violate `constraints` are marked infeasible and are
excluded from the winner.

<Note>
  The three example sets play different roles: `training_examples` feed the fit and are never
  scored, `validation_examples` are what every trial's eval scores against, and
  `calibration_examples` are a family-specific held-out slice.
</Note>

A trial that violates any `min_metric` constraint is marked `feasible: false` and cannot win,
but it is still promotable if you prefer it over the winner.

The run does not publish a blueprint per trial. Materialize the one you want with the [Promote
Trial](/api-reference/agents/optimizations/promote-trial) endpoint.

## Request

<ParamField body="blueprint_id" type="string" required>
  The blueprint to search — a `blp_` ID. Must be visible to the caller's organization.
</ParamField>

<ParamField body="objective" type="string" required>
  Primary metric name to maximize. Must be one of the objectives declared by the blueprint's
  metrics schema.
</ParamField>

<ParamField body="budget" type="object" required>
  Budget knobs for the run.

  * `max_trials` (integer, required) — how many trials the run may create. Minimum `1`.
</ParamField>

<ParamField body="validation_examples" type="array" required>
  Scoring examples — every trial's eval scores against these. Each entry is an example, in the
  same shape [Create Eval](/api-reference/agents/evals/create-eval) accepts.
</ParamField>

<ParamField body="name" type="string">
  Human label for this run.
</ParamField>

<ParamField body="search_space" type="object">
  The parameter space to sample from. Keys must match tunable blueprint values (`values.*`).
</ParamField>

<ParamField body="training_examples" type="array">
  Fit examples. Omit when the blueprint's fit needs no external training data — a Task
  Verification Agent or Manual Generation Agent run tuning inference-time knobs, for example.
  Consumed by the fit, never scored.

  <Note>
    Omit `training_examples` when the blueprint's fit needs no external training data.
  </Note>
</ParamField>

<ParamField body="calibration_examples" type="array">
  Calibration examples: a family-specific held-out slice, e.g. Activity Detection threshold
  calibration.
</ParamField>

<ParamField body="constraints" type="object">
  Per-trial feasibility constraints. A trial that fails any of them is marked
  `feasible: false` and excluded from `best_trial_id`.

  * `min_metric` (array) — "the trial's `metric` must be ≥ `min_value`" checks.
</ParamField>

### Search space (`search_space`)

Each entry names a parameter, the values it can take, and where the sampled value plugs in at
trial time.

<ParamField body="parameters" type="object" required>
  Parameter name to entry. The name is the destination key inside the entry's `kind` bucket at
  trial time.
</ParamField>

<ParamField body="parameters.<name>.kind" type="string" required>
  Which override kind the sampled value writes to: `value`, `model`, or `fitting`. Each maps to a
  distinct argument the training / eval resolution consumes.
</ParamField>

<ParamField body="parameters.<name>.spec" type="object" required>
  The domain the sampler draws from. One of three forms:

  * `{"type": "categorical", "values": [...]}` — a fixed set to sample from, e.g. `["Uniform", "Distance"]` or `[512, 1024, 2048]`. Each value is an integer or a string.
  * `{"type": "int_range", "min": 16, "max": 1024}` — an integer range, both bounds inclusive.
  * `{"type": "float_range", "min": 0.01, "max": 0.5}` — a float range, both bounds inclusive.
</ParamField>

### Metric threshold (`constraints.min_metric[]`)

<ParamField body="metric" type="string" required>
  Metric name — must be a value the trial's metrics report emits, e.g. `macro_f1` or `recall`.
</ParamField>

<ParamField body="min_value" type="number" required>
  Minimum acceptable value, inclusive.
</ParamField>

<ParamField body="class" type="string">
  When set, the threshold applies to this class's per-class value of `metric` — class
  `fault_bearing` recall, for example. Unset applies it to the aggregate.
</ParamField>

## Response

Returns `201 Created` with the run in `pending` status. See
[Get Optimization](/api-reference/agents/optimizations/get-optimization) for the full field list.

<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 being maximized.

  <Note>
    `objective` must be one of the objectives the blueprint's metrics schema declares; a
    blueprint publishing no metrics catalog cannot be optimized.
  </Note>
</ResponseField>

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

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

<ResponseField name="validation_examples" type="array" required>
  The scoring examples as resolved: named, their inputs pinned with the CRC32C of the bytes used,
  and their ground-truth declarations filled in from the blueprint's defaults.
</ResponseField>

<ResponseField name="status" type="string" required>
  Optimization lifecycle status: `pending`, `running`, `completed`, `failed`, or `cancelled`.
</ResponseField>

<ResponseField name="progress" type="object" required>
  Per-status trial counts, so a caller can render a progress bar without listing trials. All zero
  on a fresh run.
</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">
  Set by the promotion step on successful completion; the trial the run picked as its winner.
</ResponseField>

<ResponseField name="training_examples" type="array">
  The fit examples as resolved; `null` when the run supplied none.
</ResponseField>

<ResponseField name="calibration_examples" type="array">
  The calibration examples as resolved; `null` when the run supplied none.
</ResponseField>

<ResponseField name="constraints" type="object">
  The per-trial feasibility constraints; `null` when the run supplied none.
</ResponseField>

<ResponseField name="started_at" type="string">
  When the run started; `null` before then.
</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" \
    -H "Authorization: Bearer $ATAI_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "name": "Window size sweep",
      "blueprint_id": "blp_01jc9n7k3xf8mbq2v5t0ary6de",
      "objective": "macro_f1",
      "budget": {"max_trials": 24},
      "search_space": {
        "parameters": {
          "window_size": {
            "kind": "value",
            "spec": {"type": "categorical", "values": [512, 1024, 2048]}
          },
          "n_neighbors": {
            "kind": "fitting",
            "spec": {"type": "int_range", "min": 3, "max": 25}
          }
        }
      },
      "constraints": {
        "min_metric": [
          {"metric": "recall", "class": "fault_bearing", "min_value": 0.8}
        ]
      },
      "training_examples": [
        {"inputs": [{"type": "file", "id": "file_abc123", "format": "csv"}]}
      ],
      "validation_examples": [
        {"inputs": [{"type": "file", "id": "file_def456", "format": "csv"}]}
      ]
    }'
  ```

  ```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",
      headers={
          "Authorization": f"Bearer {api_key}",
          "Content-Type": "application/json",
      },
      json={
          "name": "Window size sweep",
          "blueprint_id": "blp_01jc9n7k3xf8mbq2v5t0ary6de",
          "objective": "macro_f1",
          "budget": {"max_trials": 24},
          "search_space": {
              "parameters": {
                  "window_size": {
                      "kind": "value",
                      "spec": {"type": "categorical", "values": [512, 1024, 2048]},
                  },
                  "n_neighbors": {
                      "kind": "fitting",
                      "spec": {"type": "int_range", "min": 3, "max": 25},
                  },
              }
          },
          "training_examples": [
              {"inputs": [{"type": "file", "id": "file_abc123", "format": "csv"}]}
          ],
          "validation_examples": [
              {"inputs": [{"type": "file", "id": "file_def456", "format": "csv"}]}
          ],
      },
  )

  if response.status_code == 201:
      run = response.json()
      print(f"Created {run['id']} ({run['status']}) maximising {run['objective']}")
  else:
      print(f"Error: {response.json()['errors']}")
  ```

  ```javascript JavaScript theme={"system"}
  const response = await fetch(`${process.env.ATAI_API_URL}/agents/optimizations`, {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${process.env.ATAI_API_KEY}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      name: 'Window size sweep',
      blueprint_id: 'blp_01jc9n7k3xf8mbq2v5t0ary6de',
      objective: 'macro_f1',
      budget: { max_trials: 24 },
      search_space: {
        parameters: {
          window_size: {
            kind: 'value',
            spec: { type: 'categorical', values: [512, 1024, 2048] }
          },
          n_neighbors: {
            kind: 'fitting',
            spec: { type: 'int_range', min: 3, max: 25 }
          }
        }
      },
      training_examples: [
        { inputs: [{ type: 'file', id: 'file_abc123', format: 'csv' }] }
      ],
      validation_examples: [
        { inputs: [{ type: 'file', id: 'file_def456', format: 'csv' }] }
      ]
    })
  });

  const body = await response.json();

  if (response.status === 201) {
    console.log(`Created ${body.id} (${body.status}) maximising ${body.objective}`);
  } else {
    console.error('Error:', body.errors);
  }
  ```
</RequestExample>

<ResponseExample>
  ```json 201 - Created 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]}
        },
        "n_neighbors": {
          "kind": "fitting",
          "spec": {"type": "int_range", "min": 3, "max": 25}
        }
      }
    },
    "budget": {"max_trials": 24},
    "constraints": {
      "min_metric": [
        {"metric": "recall", "class": "fault_bearing", "min_value": 0.8}
      ]
    },
    "training_examples": [
      {
        "name": "file_abc123",
        "ordinal": 1,
        "inputs": [
          {"type": "file", "id": "file_abc123", "format": "csv", "crc32c": "AAAAAA=="}
        ]
      }
    ],
    "calibration_examples": null,
    "validation_examples": [
      {
        "name": "file_def456",
        "ordinal": 1,
        "inputs": [
          {"type": "file", "id": "file_def456", "format": "csv", "crc32c": "AAAAAA=="}
        ]
      }
    ],
    "status": "pending",
    "progress": {
      "pending": 0,
      "running": 0,
      "completed": 0,
      "failed": 0,
      "cancelled": 0,
      "infeasible": 0
    },
    "best_trial_id": null,
    "created_by": "usr_01jc8m4p3rt6vx9qn2h5kdzb7y",
    "created_at": "2026-09-18T12:02:44Z",
    "started_at": null,
    "completed_at": null,
    "error": null
  }
  ```

  ```json 400 - Invalid request theme={"system"}
  {
    "errors": [
      {
        "code": "<error_code>",
        "message": "Invalid request.",
        "suggestion": null,
        "error_uid": "err-xxxxxxxx"
      }
    ]
  }
  ```

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


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