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

# Create Experiment

> Create an experiment.

When `source_experiment_id` is set, duplicates the source experiment
(block, name + "(Copy)", n_consensus, documents) and rejects any other
field. Otherwise creates a fresh experiment from the provided fields.

Create a consensus experiment on a supported block (`extract`, `classifier`,
`split`, or `for_each` configured with `map_method="split_by_key"`). The
experiment freezes a name, a fixed document set, and a consensus count — but
does NOT run metrics. Trigger the first run with
[Run Experiment](/api-reference/workflows/experiments/runs/create).

The create route is flat: send `workflow_id` in the request body.

Provide documents through one or both of:

* **`document_captures`** — references to past workflow runs. The handle
  inputs the block actually received are materialized server-side.
* **`documents`** — explicit handle inputs you assemble yourself, optionally
  carrying source metadata.

`n_consensus` must be `3`, `5`, or `7`. See [Experiments](/workflows/Experiments)
for the full conceptual model.

<RequestExample>
  ```python Python theme={null}
  from retab import Retab

  client = Retab()

  experiment = client.workflows.experiments.create(
      workflow_id="wf_abc123",
      block_id="extract-invoice",
      name="Q1 invoices",
      document_captures=[
          {"run_id": "wfrun_1"},
          {"run_id": "wfrun_2", "step_id": "for_each-0"},
      ],
      n_consensus=5,
  )
  print(experiment.id)
  ```

  ```typescript TypeScript theme={null}
  import { Retab } from "@retab/node";

  const client = new Retab({ apiKey: process.env.RETAB_API_KEY });

  const experiment = await client.workflows.experiments.create("wf_abc123", "extract-invoice", [
      { runId: "wfrun_1" },
      { runId: "wfrun_2", stepId: "for_each-0" },
    ], undefined, 5, "Q1 invoices");
  console.log(experiment.id);
  ```

  ```go Go theme={null}
  package main

  import (
  	"context"
  	"fmt"
  	"log"

  	retab "github.com/retab-dev/retab/clients/go"
  )

  func ptr[T any](v T) *T { return &v }

  func main() {
  	ctx := context.Background()

  	client, err := retab.NewClient("")
  	if err != nil {
  		log.Fatal(err)
  	}

  	experiment, err := client.Workflows.Experiments.Create(ctx, &retab.WorkflowExperimentsCreateParams{
  		WorkflowID: "wf_abc123",
  		BlockID:    ptr("extract-invoice"),
  		Name:       ptr("Q1 invoices"),
  		DocumentCaptures: []*retab.ExperimentDocumentCaptureRequest{
  			{RunID: "wfrun_1"},
  			{RunID: "wfrun_2", StepID: ptr("for_each-0")},
  		},
  		NConsensus: ptr(retab.CreateExperimentRequestNConsensus5),
  	})
  	if err != nil {
  		log.Fatal(err)
  	}

  	fmt.Println(experiment.ID)
  }
  ```

  ```ruby Ruby theme={null}
  require 'retab'

  client = Retab::Client.new(api_key: ENV['RETAB_API_KEY'])

  experiment = client.workflows.experiments.create(
    workflow_id: 'wf_abc123',
    block_id: 'extract-invoice',
    name: 'Q1 invoices',
    document_captures: [
      { run_id: 'wfrun_1' },
      { run_id: 'wfrun_2', step_id: 'for_each-0' },
    ],
    n_consensus: 5,
  )
  puts experiment.id
  ```

  ```rust Rust theme={null}
  use retab::enums::CreateExperimentRequestNConsensus;
  use retab::models::{CreateExperimentRequest, ExperimentDocumentCaptureRequest};
  use retab::resources::workflow_experiments::CreateParams;
  use retab::Retab;

  #[tokio::main]
  async fn main() -> Result<(), Box<dyn std::error::Error>> {
      let client = Retab::new(std::env::var("RETAB_API_KEY")?);

      let mut body = CreateExperimentRequest::new("wf_abc123");
      body.block_id = Some("extract-invoice".into());
      body.name = Some("Q1 invoices".into());
      body.document_captures = Some(vec![
          ExperimentDocumentCaptureRequest::new("wfrun_1"),
          ExperimentDocumentCaptureRequest {
              run_id: "wfrun_2".into(),
              step_id: Some("for_each-0".into()),
          },
      ]);
      body.n_consensus = Some(CreateExperimentRequestNConsensus::V5);

      let experiment = client
          .workflows().experiments()
          .create(CreateParams::new(body))
          .await?;
      println!("{}", experiment.id);
      Ok(())
  }
  ```

  ```php PHP theme={null}
  <?php
  require 'vendor/autoload.php';

  use Retab\Client;

  $client = new Client(apiKey: getenv('RETAB_API_KEY'));

  $result = $client->workflows()->experiments()->create(
      workflowId: 'wf_abc123',
  );
  print_r($result);
  ```

  ```csharp C# theme={null}
  using Retab;
  using RetabClient = Retab.Retab;

  var apiKey = Environment.GetEnvironmentVariable("RETAB_API_KEY")!;
  var client = new RetabClient(apiKey);

  var result = await client.Workflows.Experiments.CreateAsync(new WorkflowExperimentsCreateOptions());
  Console.WriteLine(result);
  ```

  ```java Java theme={null}
  import com.retab.RetabClient;

  public final class Example {
    public static void main(String[] args) throws Exception {
      RetabClient client = new RetabClient(System.getenv("RETAB_API_KEY"));

      var result = client.workflows().experiments().create("wf_abc123", "block_abc123", null, null, null, "Invoice Processing", null);
      System.out.println(result);
    }
  }
  ```

  ```curl cURL theme={null}
  curl -X 'POST' \
    'https://api.retab.com/v1/workflows/experiments' \
    -H 'Content-Type: application/json' \
    -H 'Authorization: Bearer <your-api-key>' \
    -d '{
      "workflow_id": "wf_abc123",
      "block_id": "extract-invoice",
      "name": "Q1 invoices",
      "document_captures": [
        { "run_id": "wfrun_1" },
        { "run_id": "wfrun_2", "step_id": "for_each-0" }
      ],
      "n_consensus": 5
    }'
  ```
</RequestExample>

<ResponseExample>
  ```json 201 theme={null}
  {
    "id": "exp_abc",
    "workflow_id": "wf_abc123",
    "block_id": "extract-invoice",
    "block_kind": "extract",
    "n_consensus": 5,
    "document_count": 2,
    "name": "Q1 invoices",
    "last_run_id": null,
    "status": "draft",
    "score": null,
    "is_stale": false,
    "schema_drift": "unknown",
    "schema_drift_detail": null,
    "created_at": "2026-05-01T14:30:00Z",
    "updated_at": "2026-05-01T14:30:00Z"
  }
  ```

  ```json 400 theme={null}
  {
    "detail": "Provide at least one document or document capture."
  }
  ```

  ```json 404 theme={null}
  {
    "detail": "Block not found: extract-invoice"
  }
  ```
</ResponseExample>


## OpenAPI

````yaml POST /v1/workflows/experiments
openapi: 3.1.0
info:
  title: FastAPI
  version: 0.1.0
servers:
  - url: https://api.retab.com
security: []
paths:
  /v1/workflows/experiments:
    post:
      tags:
        - Workflows
        - Workflow Experiments
      summary: Create Experiment
      description: |-
        Create an experiment.

        When `source_experiment_id` is set, duplicates the source experiment
        (block, name + "(Copy)", n_consensus, documents) and rejects any other
        field. Otherwise creates a fresh experiment from the provided fields.
      operationId: create_experiment
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CreateExperimentRequest'
        required: true
      responses:
        '201':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/WorkflowExperiment'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
      security:
        - HTTPBearer: []
components:
  schemas:
    CreateExperimentRequest:
      properties:
        workflow_id:
          type: string
          title: Workflow Id
        block_id:
          anyOf:
            - type: string
            - type: 'null'
          title: Block Id
        document_captures:
          anyOf:
            - items:
                $ref: '#/components/schemas/ExperimentDocumentCaptureRequest'
              type: array
            - type: 'null'
          title: Document Captures
        documents:
          anyOf:
            - items:
                $ref: '#/components/schemas/ExplicitExperimentDocumentRequest'
              type: array
            - type: 'null'
          title: Documents
        n_consensus:
          anyOf:
            - type: integer
              enum:
                - 3
                - 5
                - 7
            - type: 'null'
          title: N Consensus
        name:
          anyOf:
            - type: string
            - type: 'null'
          title: Name
        source_experiment_id:
          anyOf:
            - type: string
            - type: 'null'
          title: Source Experiment Id
      additionalProperties: false
      type: object
      required:
        - workflow_id
      title: CreateExperimentRequest
      description: |-
        Create an experiment, in one of two modes.

        - **Create from scratch** — provide `block_id`, `name`, optional
          `document_captures`/`documents`/`n_consensus`. Leave
          `source_experiment_id` unset.
        - **Duplicate an existing experiment** — provide only
          `source_experiment_id`. The source's block, name (with a `(Copy)`
          suffix), `n_consensus`, and documents are copied. All other fields
          must be omitted.

        Combining `source_experiment_id` with any other field is rejected.
    WorkflowExperiment:
      properties:
        id:
          type: string
          title: Id
        workflow_id:
          type: string
          title: Workflow Id
        block_id:
          type: string
          title: Block Id
        n_consensus:
          type: integer
          enum:
            - 3
            - 5
            - 7
          title: N Consensus
        document_count:
          type: integer
          title: Document Count
          default: 0
        name:
          type: string
          title: Name
        last_run_id:
          anyOf:
            - type: string
            - type: 'null'
          title: Last Run Id
        created_at:
          type: string
          format: date-time
          title: Created At
          description: When the experiment was created
        updated_at:
          type: string
          format: date-time
          title: Updated At
          description: When the experiment was last updated
        status:
          type: string
          enum:
            - draft
            - processing
            - completed
            - failed
            - cancelled
          title: Status
          default: draft
        block_type:
          type: string
          enum:
            - extract
            - classifier
            - split
            - for_each
          title: Block Type
        score:
          anyOf:
            - type: number
            - type: 'null'
          title: Score
        is_stale:
          type: boolean
          title: Is Stale
          default: false
        freshness:
          $ref: '#/components/schemas/ArtifactFreshness'
        freshness_state:
          type: string
          enum:
            - fresh
            - stale
            - unknown
          title: Freshness State
          default: unknown
        freshness_reasons:
          items:
            type: string
          type: array
          title: Freshness Reasons
          default: []
        run_plan_mode:
          type: string
          enum:
            - run
            - noop
            - conflict
            - unknown
          title: Run Plan Mode
          default: unknown
        rerunnable_document_count:
          type: integer
          title: Rerunnable Document Count
          default: 0
        schema_drift:
          type: string
          enum:
            - none
            - partial
            - drifted
            - unknown
          title: Schema Drift
          default: unknown
        schema_drift_detail:
          anyOf:
            - type: string
            - type: 'null'
          title: Schema Drift Detail
        drift:
          $ref: '#/components/schemas/ArtifactDrift'
      type: object
      required:
        - block_id
        - block_type
        - id
        - n_consensus
        - name
        - workflow_id
      title: WorkflowExperiment
      description: >-
        An experiment that evaluates a workflow block against a set of
        documents, with its latest run status and score.
    HTTPValidationError:
      properties:
        detail:
          items:
            $ref: '#/components/schemas/ValidationError'
          type: array
          title: Detail
          default: []
      type: object
      title: HTTPValidationError
    ExperimentDocumentCaptureRequest:
      properties:
        run_id:
          type: string
          title: Run Id
        step_id:
          anyOf:
            - type: string
            - type: 'null'
          title: Step Id
      additionalProperties: false
      type: object
      required:
        - run_id
      title: ExperimentDocumentCaptureRequest
      description: Capture one experiment document from workflow execution provenance.
    ExplicitExperimentDocumentRequest:
      properties:
        handle_inputs:
          additionalProperties:
            oneOf:
              - $ref: '#/components/schemas/JsonHandleInput'
              - $ref: '#/components/schemas/FileHandleInput'
            discriminator:
              propertyName: type
              mapping:
                file:
                  $ref: '#/components/schemas/FileHandleInput'
                json:
                  $ref: '#/components/schemas/JsonHandleInput'
          type: object
          title: Handle Inputs
        provenance:
          anyOf:
            - $ref: '#/components/schemas/ExperimentDocumentProvenance'
            - type: 'null'
      additionalProperties: false
      type: object
      required:
        - handle_inputs
      title: ExplicitExperimentDocumentRequest
    ArtifactFreshness:
      properties:
        status:
          type: string
          enum:
            - fresh
            - stale
            - unknown
          title: Status
          default: unknown
        reasons:
          items:
            type: string
            enum:
              - validity_changed
              - inputs_changed
              - engine_changed
              - metrics_engine_changed
              - no_baseline
          type: array
          title: Reasons
          default: []
        validity_fingerprint:
          anyOf:
            - type: string
            - type: 'null'
          title: Validity Fingerprint
        input_fingerprint:
          anyOf:
            - type: string
            - type: 'null'
          title: Input Fingerprint
        baseline_run_id:
          anyOf:
            - type: string
            - type: 'null'
          title: Baseline Run Id
      type: object
      title: ArtifactFreshness
    ArtifactDrift:
      properties:
        status:
          type: string
          enum:
            - none
            - drifted
            - broken
            - unknown
          title: Status
          default: unknown
        affected_targets:
          items:
            type: string
          type: array
          title: Affected Targets
          default: []
        detail:
          anyOf:
            - type: string
            - type: 'null'
          title: Detail
      type: object
      title: ArtifactDrift
    ValidationError:
      properties:
        loc:
          items:
            anyOf:
              - type: string
              - type: integer
          type: array
          title: Location
        msg:
          type: string
          title: Message
        type:
          type: string
          title: Error Type
        input:
          title: Input
          default: null
        ctx:
          type: object
          title: Context
          default: {}
      type: object
      required:
        - loc
        - msg
        - type
      title: ValidationError
    JsonHandleInput:
      properties:
        type:
          type: string
          const: json
          title: Type
          default: json
        data:
          title: Data
          default: null
      additionalProperties: false
      type: object
      title: JsonHandleInput
      description: JSON payload for a handle input. `data` is the raw JSON value.
    FileHandleInput:
      properties:
        type:
          type: string
          const: file
          title: Type
          default: file
        document:
          $ref: '#/components/schemas/ResultFileRef'
      additionalProperties: false
      type: object
      required:
        - document
      title: FileHandleInput
      description: File reference for a handle input.
    ExperimentDocumentProvenance:
      properties:
        run_id:
          anyOf:
            - type: string
            - type: 'null'
          title: Run Id
        step_id:
          anyOf:
            - type: string
            - type: 'null'
          title: Step Id
      type: object
      title: ExperimentDocumentProvenance
      description: Workflow execution metadata attached to a captured document.
    ResultFileRef:
      properties:
        id:
          type: string
          title: Id
          description: ID of the file
        filename:
          type: string
          title: Filename
          description: Filename of the file
        mime_type:
          type: string
          title: Mime Type
          description: MIME type of the file
      type: object
      required:
        - filename
        - id
        - mime_type
      title: ResultFileRef
      description: Public/shared file reference used across SDK and customer-facing APIs.
  securitySchemes:
    HTTPBearer:
      type: http
      scheme: bearer

````