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

> Create a partition.

Groups the pages of a `document` into chunks by a partition `key`, guided by
`instructions` and the chosen `model`. Set `n_consensus` above `1` to run multiple
votes and consolidate them, and `allow_overlap` to let a page belong to more than one
chunk. Returns the stored `Partition` with its `output` chunks, and responds with `201`.

Partition a document into repeated chunks keyed by a value such as `invoice_number`, `policy_id`, or `claim_number`.

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

  client = Retab()

  document = MIMEData(
      filename="invoice_batch.pdf",
      url="https://my-bucket.s3.us-east-1.amazonaws.com/documents/invoice_batch.pdf",
  )

  response = client.partitions.create(
      document=document,
      key="invoice_number",
      instructions="Return one chunk per invoice number and keep all pages for the same invoice together.",
      model="retab-small",
      n_consensus=3,
      allow_overlap=True,
      bust_cache=False,
  )

  for chunk in response.output:
      print(chunk.key, chunk.pages)
  ```

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

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

  const document = {
    filename: "invoice_batch.pdf",
    url: "https://my-bucket.s3.us-east-1.amazonaws.com/documents/invoice_batch.pdf",
  };

  const response = await client.partitions.create(document, "invoice_number", "Return one chunk per invoice number and keep all pages for the same invoice together.", "retab-small", 3, true, false);

  for (const chunk of response.output) {
    console.log(chunk.key, chunk.pages);
  }
  ```

  ```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)
  	}

  	document := retab.MIMEData{
  		Filename: "invoice_batch.pdf",
  		URL:      "https://my-bucket.s3.us-east-1.amazonaws.com/documents/invoice_batch.pdf",
  	}

  	response, err := client.Partitions.Create(ctx, &retab.PartitionsCreateParams{
  		Document:     document,
  		Key:          "invoice_number",
  		Instructions: "Return one chunk per invoice number and keep all pages for the same invoice together.",
  		Model:        ptr("retab-small"),
  		NConsensus:   ptr(3),
  		AllowOverlap: ptr(true),
  		BustCache:    ptr(false),
  	})
  	if err != nil {
  		log.Fatal(err)
  	}

  	for _, chunk := range response.Output {
  		fmt.Println(chunk.Key, chunk.Pages)
  	}
  }
  ```

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

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

  document = {
    filename: 'invoice_batch.pdf',
    url: 'https://my-bucket.s3.us-east-1.amazonaws.com/documents/invoice_batch.pdf',
  }

  response = client.partitions.create(
    document: document,
    key: 'invoice_number',
    instructions: 'Return one chunk per invoice number and keep all pages for the same invoice together.',
    model: 'retab-small',
    n_consensus: 3,
    allow_overlap: true,
    bust_cache: false,
  )

  response.output.each do |chunk|
    puts "#{chunk.key} #{chunk.pages}"
  end
  ```

  ```rust Rust theme={null}
  use retab::resources::partitions::CreateParams;
  use retab::{MimeData, Retab};

  #[tokio::main]
  async fn main() -> Result<(), Box<dyn std::error::Error>> {
      let client = Retab::new(std::env::var("RETAB_API_KEY")?);
      let document = MimeData::new(
          "invoice_batch.pdf",
          "https://my-bucket.s3.us-east-1.amazonaws.com/documents/invoice_batch.pdf",
      );

      let mut params = CreateParams::new(
          document,
          "invoice_number",
          "Return one chunk per invoice number and keep all pages for the same invoice together.",
      );
      params.body.model = Some("retab-small".into());
      params.body.n_consensus = Some(3);
      params.body.allow_overlap = Some(true);
      params.body.bust_cache = Some(false);

      let response = client.partitions().create(params).await?;

      for chunk in response.output.as_ref().map(|v| v.as_slice()).unwrap_or_default() {
          println!("{} {:?}", chunk.key, chunk.pages.as_ref().unwrap_or(&vec![]));
      }
      Ok(())
  }
  ```

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

  use Retab\Client;

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

  $result = $client->partitions()->create(
      document: [
          'filename' => 'invoice_batch.pdf',
          'url' => 'https://my-bucket.s3.us-east-1.amazonaws.com/documents/invoice_batch.pdf',
      ],
      key: 'value',
      instructions: 'value',
  );
  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 document = MimeData.FromUrl(new Uri("https://my-bucket.s3.us-east-1.amazonaws.com/documents/invoice_batch.pdf"));

  var result = await client.Partitions.CreateAsync(new PartitionsCreateOptions
  {
      Document = document,
      Key = "invoice_number",
      Instructions = "Return one chunk per invoice number and keep all pages for the same invoice together.",
      Model = "retab-small",
      NConsensus = 3,
      AllowOverlap = true,
      BustCache = false,
  });
  Console.WriteLine(result);
  ```

  ```java Java theme={null}
  import com.retab.RetabClient;
  import com.retab.models.MimeData;
  import java.net.URI;

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

      MimeData document = MimeData.fromUrl(
          URI.create("https://my-bucket.s3.us-east-1.amazonaws.com/documents/invoice_batch.pdf"));

      var result = client.partitions().create(
          document,
          "invoice_number",
          "Return one chunk per invoice number and keep all pages for the same invoice together.",
          "retab-small",
          3L,
          true,
          false,
          null);
      System.out.println(result);
    }
  }
  ```

  ```curl cURL theme={null}
  curl -X POST \
    'https://api.retab.com/v1/partitions' \
    -H "Authorization: Bearer $RETAB_API_KEY" \
    -H 'Content-Type: application/json' \
    -d '{
    "document": {
      "filename": "invoice_batch.pdf",
      "url": "https://my-bucket.s3.us-east-1.amazonaws.com/documents/invoice_batch.pdf"
    },
    "key": "invoice_number",
    "instructions": "Return one chunk per invoice number and keep all pages for the same invoice together.",
    "model": "retab-small",
    "n_consensus": 3,
    "allow_overlap": true,
    "bust_cache": false
  }'
  ```
</RequestExample>

<ResponseExample>
  ```json 200 theme={null}
  {
    "output": [
      {
        "key": "INV-001",
        "pages": [1, 2]
      },
      {
        "key": "INV-002",
        "pages": [3, 4]
      }
    ],
    "consensus": {
      "likelihoods": [
        {
          "key": 0.99,
          "pages": [0.99, 0.98]
        },
        {
          "key": 0.96,
          "pages": [0.95, 0.95]
        }
      ],
      "choices": [
        [
          { "key": "INV-001", "pages": [1, 2] },
          { "key": "INV-002", "pages": [3, 4] }
        ],
        [
          { "key": "INV-001", "pages": [1, 2] },
          { "key": "INV-002", "pages": [3, 4] }
        ],
        [
          { "key": "INV-001", "pages": [1, 2] },
          { "key": "INV-002", "pages": [3, 4] }
        ]
      ]
    },
    "usage": {
      "credits": 3.0
    }
  }
  ```
</ResponseExample>


## OpenAPI

````yaml POST /v1/partitions
openapi: 3.1.0
info:
  title: FastAPI
  version: 0.1.0
servers:
  - url: https://api.retab.com
security: []
paths:
  /v1/partitions:
    post:
      tags:
        - Partitions
      summary: Create Partitions
      description: >-
        Create a partition.


        Groups the pages of a `document` into chunks by a partition `key`,
        guided by

        `instructions` and the chosen `model`. Set `n_consensus` above `1` to
        run multiple

        votes and consolidate them, and `allow_overlap` to let a page belong to
        more than one

        chunk. Returns the stored `Partition` with its `output` chunks, and
        responds with `201`.
      operationId: create_partitions
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CreatePartitionRequest'
        required: true
      responses:
        '201':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Partition'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
      security:
        - HTTPBearer: []
components:
  schemas:
    CreatePartitionRequest:
      properties:
        document:
          $ref: '#/components/schemas/MIMEData'
          description: The document to partition
        key:
          type: string
          title: Key
          description: The key to partition the document by
        instructions:
          type: string
          title: Instructions
          description: Instructions describing how the document should be partitioned
        model:
          type: string
          title: Model
          description: The model to use for partitioning
          default: retab-small
        n_consensus:
          type: integer
          title: N Consensus
          description: >-
            Number of partitioning runs to use for consensus voting. Uses
            deterministic single-pass when set to 1.
          default: 1
        allow_overlap:
          type: boolean
          title: Allow Overlap
          description: If true, allow a page to appear in more than one partition chunk
          default: true
        bust_cache:
          type: boolean
          title: Bust Cache
          description: If true, skip the LLM cache and force a fresh completion
          default: false
        background:
          type: boolean
          title: Background
          description: >-
            If true, run asynchronously: returns immediately with status
            'queued' and an empty output. Poll GET /v1/<primitive>/{id} until
            status is terminal. Mutually exclusive with stream.
          default: false
      type: object
      required:
        - document
        - instructions
        - key
      title: CreatePartitionRequest
      description: Public create-partition request body.
    Partition:
      properties:
        id:
          type: string
          title: Id
          description: Unique identifier of the partition
        file:
          $ref: '#/components/schemas/FileRef'
          description: Information about the partitioned file
        model:
          type: string
          title: Model
          description: Model used for the partition operation
        key:
          type: string
          title: Key
          description: Partition key used for the run
        instructions:
          anyOf:
            - type: string
            - type: 'null'
          title: Instructions
          description: Free-form instructions supplied with the partition request
        n_consensus:
          type: integer
          title: N Consensus
          description: Number of consensus votes used
          default: 1
        allow_overlap:
          type: boolean
          title: Allow Overlap
          description: >-
            Whether pages were allowed to appear in more than one partition
            chunk
          default: true
        output:
          items:
            $ref: '#/components/schemas/PartitionChunk'
          type: array
          title: Output
          description: >-
            The list of partition chunks with their assigned pages. Empty []
            until status == 'completed'.
          default: []
        status:
          type: string
          enum:
            - pending
            - queued
            - in_progress
            - completed
            - failed
            - cancelled
          title: Status
          description: >-
            Lifecycle status. The synchronous path returns 'completed'.
            Background runs progress pending -> queued -> in_progress ->
            completed | failed | cancelled.
          default: pending
        error:
          anyOf:
            - $ref: '#/components/schemas/PrimitiveError'
            - type: 'null'
          description: >-
            Error details when a background run fails; null otherwise. Always
            present so consumers can read it without an existence check.
        consensus:
          anyOf:
            - $ref: '#/components/schemas/PartitionConsensus'
            - type: 'null'
          description: Consensus metadata for multi-vote partition runs
        usage:
          anyOf:
            - $ref: '#/components/schemas/RetabUsage'
            - type: 'null'
          description: Usage information for the partition operation
        created_at:
          anyOf:
            - type: string
              format: date-time
            - type: 'null'
          title: Created At
      type: object
      required:
        - file
        - id
        - key
        - model
      title: Partition
      description: >-
        A partition result: a document segmented into chunks along the requested
        `key`.
    HTTPValidationError:
      properties:
        detail:
          items:
            $ref: '#/components/schemas/ValidationError'
          type: array
          title: Detail
          default: []
      type: object
      title: HTTPValidationError
    MIMEData:
      properties:
        filename:
          type: string
          title: Filename
          description: The filename of the file
          examples:
            - file.pdf
            - image.png
            - data.txt
        url:
          type: string
          title: Url
          description: The URL of the file in base64 format
          examples:
            - data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIA...
      additionalProperties: false
      type: object
      required:
        - filename
        - url
      title: MIMEData
      description: A file represented by its `filename` and a base64 data `url`.
    FileRef:
      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: FileRef
      description: Public/shared file reference used across SDK and customer-facing APIs.
    PartitionChunk:
      properties:
        key:
          type: string
          title: Key
          description: The partition key value for this chunk
        pages:
          items:
            type: integer
          type: array
          title: Pages
          description: The pages assigned to this partition chunk (1-indexed)
          default: []
      type: object
      required:
        - key
      title: PartitionChunk
    PrimitiveError:
      properties:
        code:
          type: string
          title: Code
          description: Machine-readable error code.
        message:
          type: string
          title: Message
          description: Human-readable error message.
        details:
          anyOf:
            - additionalProperties: true
              type: object
            - type: 'null'
          title: Details
          description: Optional structured error context.
      type: object
      required:
        - code
        - message
      title: PrimitiveError
    PartitionConsensus:
      properties:
        choices:
          items:
            items:
              $ref: '#/components/schemas/PartitionChunk'
            type: array
          type: array
          title: Choices
          description: >-
            Alternative partition vote outputs used to build the consolidated
            result.
          default: []
        likelihoods:
          items:
            $ref: '#/components/schemas/PartitionChunkLikelihood'
          type: array
          title: Likelihoods
          description: Consensus likelihoods aligned with the partition output.
          default: []
      type: object
      title: PartitionConsensus
    RetabUsage:
      properties:
        credits:
          type: number
          title: Credits
          description: Credits consumed for processing
      type: object
      required:
        - credits
      title: RetabUsage
      description: Usage information for document processing.
    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
    PartitionChunkLikelihood:
      properties:
        key:
          anyOf:
            - type: number
            - type: 'null'
          title: Key
          description: Confidence that this partition key value is correct
        pages:
          items:
            type: number
          type: array
          title: Pages
          description: >-
            Confidence for each page in the corresponding partition chunk.pages
            array
          default: []
      type: object
      title: PartitionChunkLikelihood
  securitySchemes:
    HTTPBearer:
      type: http
      scheme: bearer

````