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

> Classify a document.

Runs a classification on the supplied `document` against the provided
`categories`. Tune the run with `model`, `instructions`, `first_n_pages`
(limit to the first pages), and `n_consensus` (number of votes to combine).
Returns the created classification with the chosen category and reasoning;
responds with `201`.

Classify a document into one of the provided categories and persist the result as a `Classification` resource that can later be retrieved via `GET /v1/classifications/{classification_id}` or listed via `GET /v1/classifications`.

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

  client = Retab()

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

  classification = client.classifications.create(
      document=document,
      model="retab-small",
      categories=[
          {"name": "invoice", "description": "Invoice documents with billing information"},
          {"name": "receipt", "description": "Receipt documents for payments"},
          {"name": "contract", "description": "Legal contract documents"},
      ],
      first_n_pages=3,
      instructions="Processing batch from Q4 2024 vendor submissions",
      n_consensus=1,
  )

  print(f"Classification ID: {classification.id}")
  print(f"Category: {classification.output.category}")
  print(f"Reasoning: {classification.output.reasoning}")
  ```

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

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

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

  const classification = await client.classifications.create(document, [
      {
        name: "invoice",
        description: "Invoice documents with billing information",
      },
      { name: "receipt", description: "Receipt documents for payments" },
      { name: "contract", description: "Legal contract documents" },
    ], "retab-small", 3, "Processing batch from Q4 2024 vendor submissions", 1);

  console.log(`Classification ID: ${classification.id}`);
  console.log(`Category: ${classification.output.category}`);
  ```

  ```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.pdf",
  		URL:      "https://my-bucket.s3.us-east-1.amazonaws.com/documents/invoice.pdf",
  	}

  	classification, err := client.Classifications.Create(ctx, &retab.ClassificationsCreateParams{
  		Document: document,
  		Model:    ptr("retab-small"),
  		Categories: []*retab.Category{
  			{Name: "invoice", Description: ptr("Invoice documents with billing information")},
  			{Name: "receipt", Description: ptr("Receipt documents for payments")},
  			{Name: "contract", Description: ptr("Legal contract documents")},
  		},
  		FirstNPages:  ptr(3),
  		Instructions: ptr("Processing batch from Q4 2024 vendor submissions"),
  		NConsensus:   ptr(1),
  	})
  	if err != nil {
  		log.Fatal(err)
  	}

  	fmt.Printf("Classification ID: %s\n", classification.ID)
  	fmt.Printf("Category: %s\n", classification.Output.Category)
  }
  ```

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

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

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

  classification = client.classifications.create(
    document: document,
    model: 'retab-small',
    categories: [
      { 'name' => 'invoice', 'description' => 'Invoice documents with billing information' },
      { 'name' => 'receipt', 'description' => 'Receipt documents for payments' },
      { 'name' => 'contract', 'description' => 'Legal contract documents' },
    ],
    first_n_pages: 3,
    instructions: 'Processing batch from Q4 2024 vendor submissions',
    n_consensus: 1,
  )

  puts "Classification ID: #{classification.id}"
  puts "Category: #{classification.output.category}"
  puts "Reasoning: #{classification.output.reasoning}"
  ```

  ```rust Rust theme={null}
  use retab::models::Category;
  use retab::resources::classifications::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 categories = vec![
          Category {
              name: "invoice".into(),
              handle_key: None,
              description: Some("Invoice documents with billing information".into()),
          },
          Category {
              name: "receipt".into(),
              handle_key: None,
              description: Some("Receipt documents for payments".into()),
          },
          Category {
              name: "contract".into(),
              handle_key: None,
              description: Some("Legal contract documents".into()),
          },
      ];
      let document = MimeData::new(
          "invoice.pdf",
          "https://my-bucket.s3.us-east-1.amazonaws.com/documents/invoice.pdf",
      );

      let mut params = CreateParams::new(document, categories);
      params.body.model = Some("retab-small".into());
      params.body.first_n_pages = Some(3);
      params.body.instructions = Some("Processing batch from Q4 2024 vendor submissions".into());
      params.body.n_consensus = Some(1);

      let classification = client.classifications().create(params).await?;

      println!("Classification ID: {}", classification.id);
      println!("Category: {}", classification.output.as_ref().unwrap().category);
      println!("Reasoning: {}", classification.output.as_ref().unwrap().reasoning);
      Ok(())
  }
  ```

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

  use Retab\Client;

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

  $result = $client->classifications()->create(
      document: [
          'filename' => 'invoice.pdf',
          'url' => 'https://my-bucket.s3.us-east-1.amazonaws.com/documents/invoice.pdf',
      ],
      categories: [['name' => 'invoice', 'description' => 'Invoice documents']],
  );
  print_r($result);
  ```

  ```csharp C# theme={null}
  using System;
  using System.Collections.Generic;
  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.pdf"));

  var result = await client.Classifications.CreateAsync(new ClassificationsCreateOptions
  {
      Document = document,
      Model = "retab-small",
      Categories = new List<Category>
      {
          new Category { Name = "invoice", Description = "Invoice documents with billing information" },
          new Category { Name = "receipt", Description = "Receipt documents for payments" },
          new Category { Name = "contract", Description = "Legal contract documents" },
      },
      FirstNPages = 3,
      Instructions = "Processing batch from Q4 2024 vendor submissions",
      NConsensus = 1,
  });
  Console.WriteLine(result);
  ```

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

  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.pdf"));

      List<Category> categories = List.of(
          new Category("invoice", null, "Invoice documents with billing information"),
          new Category("receipt", null, "Receipt documents for payments"),
          new Category("contract", null, "Legal contract documents"));

      var result = client.classifications().create(
          document,
          categories,
          "retab-small",
          3L,
          "Processing batch from Q4 2024 vendor submissions",
          1L,
          null,
          null);
      System.out.println(result);
    }
  }
  ```

  ```curl cURL theme={null}
  curl -X POST \
    'https://api.retab.com/v1/classifications' \
    -H "Authorization: Bearer $RETAB_API_KEY" \
    -H 'Content-Type: application/json' \
    -d '{
    "document": {
      "filename": "invoice.pdf",
      "url": "https://my-bucket.s3.us-east-1.amazonaws.com/documents/invoice.pdf"
    },
    "model": "retab-small",
    "categories": [
      {"name": "invoice", "description": "Invoice documents with billing information"},
      {"name": "receipt", "description": "Receipt documents for payments"},
      {"name": "contract", "description": "Legal contract documents"}
    ],
    "first_n_pages": 3,
    "instructions": "Processing batch from Q4 2024 vendor submissions",
    "n_consensus": 1
  }'
  ```
</RequestExample>

<ResponseExample>
  ```json 200 theme={null}
  {
    "id": "cls_01G34H8J2K",
    "file": {
      "id": "file_6dd6eb00688ad8d1",
      "filename": "invoice.pdf",
      "mime_type": "application/pdf"
    },
    "model": "retab-small",
    "categories": [
      {
        "name": "invoice",
        "description": "Invoice documents with billing information"
      },
      { "name": "receipt", "description": "Receipt documents for payments" },
      { "name": "contract", "description": "Legal contract documents" }
    ],
    "n_consensus": 1,
    "instructions": "Processing batch from Q4 2024 vendor submissions",
    "output": {
      "reasoning": "The document contains billing details including line items, unit prices, quantities, and a total amount due.",
      "category": "invoice"
    },
    "consensus": {
      "choices": [],
      "likelihood": null
    },
    "usage": {
      "prompt_tokens": 1500,
      "completion_tokens": 40,
      "total_tokens": 1540
    },
    "created_at": "2024-03-15T10:30:00Z"
  }
  ```
</ResponseExample>


## OpenAPI

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


        Runs a classification on the supplied `document` against the provided

        `categories`. Tune the run with `model`, `instructions`, `first_n_pages`

        (limit to the first pages), and `n_consensus` (number of votes to
        combine).

        Returns the created classification with the chosen category and
        reasoning;

        responds with `201`.
      operationId: create_classification
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CreateClassificationRequest'
        required: true
      responses:
        '201':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Classification'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
      security:
        - HTTPBearer: []
components:
  schemas:
    CreateClassificationRequest:
      properties:
        document:
          $ref: '#/components/schemas/MIMEData'
          description: The document to classify
        categories:
          items:
            $ref: '#/components/schemas/Category'
          type: array
          minItems: 1
          title: Categories
          description: The categories to classify the document into
        model:
          type: string
          title: Model
          description: The model to use for classification
          default: retab-small
        first_n_pages:
          anyOf:
            - type: integer
            - type: 'null'
          title: First N Pages
          description: >-
            Only use the first N pages of the document for classification.
            Useful for large documents where classification can be determined
            from early pages.
        instructions:
          anyOf:
            - type: string
            - type: 'null'
          title: Instructions
          description: >-
            Free-form instructions appended to the system prompt to steer the
            classification.
        n_consensus:
          type: integer
          title: N Consensus
          description: >-
            Number of classification runs to use for consensus voting. Uses
            deterministic single-pass when set to 1.
          default: 1
        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:
        - categories
        - document
      title: CreateClassificationRequest
      description: Public create-classification request body.
    Classification:
      properties:
        id:
          type: string
          title: Id
          description: Unique identifier of the classification
        file:
          $ref: '#/components/schemas/FileRef'
          description: Information about the classified file
        model:
          type: string
          title: Model
          description: Model used for classification
        categories:
          items:
            $ref: '#/components/schemas/Category'
          type: array
          title: Categories
          description: Categories the document was classified against
        n_consensus:
          type: integer
          title: N Consensus
          description: Number of consensus votes used
          default: 1
        instructions:
          anyOf:
            - type: string
            - type: 'null'
          title: Instructions
          description: Free-form instructions supplied with the classification request.
        output:
          $ref: '#/components/schemas/ClassificationDecision'
          description: >-
            The classification result with reasoning. A degenerate empty
            decision until status == 'completed'; gate reads on status.
        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/ClassificationConsensus'
            - type: 'null'
          description: Consensus metadata for multi-vote classification runs
        usage:
          anyOf:
            - $ref: '#/components/schemas/RetabUsage'
            - type: 'null'
          description: Usage information for the classification
        created_at:
          anyOf:
            - type: string
              format: date-time
            - type: 'null'
          title: Created At
      type: object
      required:
        - categories
        - file
        - id
        - model
      title: Classification
      description: >-
        A classification result: the categories a document was scored against
        and the chosen `output` decision.
    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`.
    Category:
      properties:
        name:
          type: string
          title: Name
          description: The name of the category
        handle_key:
          anyOf:
            - type: string
            - type: 'null'
          title: Handle Key
          description: Stable machine key used by workflow classifier output handles
        description:
          type: string
          title: Description
          description: The description of the category
          default: ''
      type: object
      required:
        - name
      title: Category
    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.
    ClassificationDecision:
      properties:
        reasoning:
          type: string
          title: Reasoning
          description: The reasoning for the classification decision
        category:
          type: string
          title: Category
          description: The category name that the document belongs to
      type: object
      required:
        - category
        - reasoning
      title: ClassificationDecision
    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
    ClassificationConsensus:
      properties:
        choices:
          items:
            $ref: '#/components/schemas/ClassificationDecision'
          type: array
          title: Choices
          description: >-
            Alternative classification vote outputs used to build the
            consolidated result.
          default: []
        likelihoods:
          type: number
          title: Likelihoods
          description: Consensus likelihood score (0.0-1.0) of the winning classification.
          default: 0
      type: object
      title: ClassificationConsensus
    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
  securitySchemes:
    HTTPBearer:
      type: http
      scheme: bearer

````