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

# Extrair dados estruturados

> Defina um esquema de extração reutilizável na API MKA1 e extraia campos estruturados de arquivos.

Use o recurso Extract quando quiser que a API MKA1 transforme um documento ou imagem enviado em JSON estruturado.
Você pode definir o esquema inline para uma solicitação pontual ou salvar um modelo de esquema reutilizável primeiro.

## Criar um esquema reutilizável

Salve um modelo de esquema quando quiser executar o mesmo formato de extração várias vezes.

<CodeGroup>
  ```bash CLI theme={null}
  mka1 llm extract create-schema \
    -H 'X-On-Behalf-Of: <end-user-id>' \
    --body '{
      "name": "Extração de nota fiscal",
      "description": "Extrair campos do cabeçalho de notas fiscais em PDF",
      "schema": {
        "type": "object",
        "properties": {
          "invoice_number": { "type": "string" },
          "vendor_name": { "type": "string" },
          "total_amount": { "type": "number" },
          "date": { "type": "string", "format": "date" }
        },
        "required": ["invoice_number", "total_amount"]
      },
      "metadata": { "document_type": "invoice" }
    }'
  ```

  ```ts MKA1 SDK theme={null}
  import { SDK } from '@meetkai/mka1';

  const mka1 = new SDK({
    apiKey: '<mka1-api-key>',
    headers: { 'X-On-Behalf-Of': '<end-user-id>' },
  });

  const schema = await mka1.llm.extract.createSchema({
    name: 'Extração de nota fiscal',
    description: 'Extrair campos do cabeçalho de notas fiscais em PDF',
    schema: {
      type: 'object',
      properties: {
        invoice_number: { type: 'string' },
        vendor_name: { type: 'string' },
        total_amount: { type: 'number' },
        date: { type: 'string', format: 'date' },
      },
      required: ['invoice_number', 'total_amount'],
    },
    metadata: {
      document_type: 'invoice',
    },
  });

  console.log(schema.id); // e.g. "schema_invoice_123"
  ```

  ```csharp C# SDK theme={null}
  using MeetKai.MKA1;
  using MeetKai.MKA1.Types.Components;

  var sdk = new SDK(
      bearerAuth: $"Bearer {YOUR_API_KEY}",
      serverUrl: "https://apigw.mka1.com"
  );

  // The Extract API is available at sdk.Llm.Extract
  // Use sdk.Llm.Extract.CreateSchema(...) to save a reusable schema
  // Refer to the API reference for the full method signature and types
  ```

  ```python Python SDK theme={null}
  from mka1 import SDK

  sdk = SDK(bearer_auth="Bearer YOUR_API_KEY")

  schema = sdk.llm.extract.create_schema(
      name="Extração de nota fiscal",
      description="Extrair campos do cabeçalho de notas fiscais em PDF",
      schema={
          "type": "object",
          "properties": {
              "invoice_number": {"type": "string"},
              "vendor_name": {"type": "string"},
              "total_amount": {"type": "number"},
              "date": {"type": "string", "format": "date"},
          },
          "required": ["invoice_number", "total_amount"],
      },
  )

  print(schema.data.id)  # e.g. "schema_invoice_123"
  ```

  ```bash bash theme={null}
  curl https://apigw.mka1.com/api/v1/llm/extract/schema \
    --request POST \
    --header 'Content-Type: application/json' \
    --header 'Authorization: Bearer <mka1-api-key>' \
    --header 'X-On-Behalf-Of: <end-user-id>' \
    --data '{
      "name": "Extração de nota fiscal",
      "description": "Extrair campos do cabeçalho de notas fiscais em PDF",
      "schema": {
        "type": "object",
        "properties": {
          "invoice_number": {
            "type": "string"
          },
          "vendor_name": {
            "type": "string"
          },
          "total_amount": {
            "type": "number"
          },
          "date": {
            "type": "string",
            "format": "date"
          }
        },
        "required": [
          "invoice_number",
          "total_amount"
        ]
      },
      "metadata": {
        "document_type": "invoice"
      }
    }'
  ```
</CodeGroup>

Isso retorna um ID de esquema como `schema_invoice_123`.

## Extrair com o esquema salvo

Use o ID do esquema salvo para extrair dados de um arquivo.
A especificação OpenAPI suporta `multipart/form-data` para esta solicitação.

<CodeGroup>
  ```bash CLI theme={null}
  mka1 llm extract extract-with-schema \
    --schema-id schema_invoice_123 \
    --model meetkai:functionary-pt \
    --prompt 'Extraia os campos estruturados da nota fiscal.' \
    --file ./invoice.pdf
  ```

  ```ts MKA1 SDK theme={null}
  const file = Bun.file('./invoice.pdf');

  const result = await mka1.llm.extract.extractWithSchema({
    schemaId: 'schema_invoice_123',
    extractWithSchemaRequestBody: {
      model: 'meetkai:functionary-pt',
      prompt: 'Extraia os campos estruturados da nota fiscal.',
      file,
    },
  });

  console.log(result.data);
  ```

  ```csharp C# SDK theme={null}
  using MeetKai.MKA1;
  using MeetKai.MKA1.Types.Requests;

  var sdk = new SDK(bearerAuth: "Bearer YOUR_API_KEY");

  var fileContent = await File.ReadAllBytesAsync("./invoice.pdf");

  var result = await sdk.Llm.Extract.ExtractWithSchemaAsync(
      "schema_invoice_123",
      new ExtractWithSchemaRequestBody()
      {
          Model = "meetkai:functionary-pt",
          Prompt = "Extraia os campos estruturados da nota fiscal.",
          File = new ExtractWithSchemaFile()
          {
              FileName = "invoice.pdf",
              Content = fileContent,
          },
      }
  );

  Console.WriteLine(result.ExtractionResponse?.Data);
  ```

  ```python Python SDK theme={null}
  result = sdk.llm.extract.extract_with_schema(
      schema_id="schema_invoice_123",
      model="meetkai:functionary-pt",
      file={
          "file_name": "invoice.pdf",
          "content": open("./invoice.pdf", "rb"),
      },
  )

  print(result.data)
  ```

  ```bash bash theme={null}
  curl https://apigw.mka1.com/api/v1/llm/extract/schema/schema_invoice_123 \
    --request POST \
    --header 'Authorization: Bearer <mka1-api-key>' \
    --header 'X-On-Behalf-Of: <end-user-id>' \
    --form 'model=meetkai:functionary-pt' \
    --form 'prompt=Extraia os campos estruturados da nota fiscal.' \
    --form 'file=@./invoice.pdf'
  ```
</CodeGroup>

Uma resposta bem-sucedida retorna um objeto JSON com:

* `success`
* `data` contendo os campos extraídos
* `metadata` sobre a execução da extração

## Use um esquema inline para trabalhos pontuais

Se você não precisa reutilizar o esquema, chame `POST /api/v1/llm/extract` em vez disso.
Forneça seu JSON Schema inline juntamente com os campos da solicitação de extração.

Nota: na especificação OpenAPI, este endpoint é definido como `application/json` (o campo `file` é enviado como uma string codificada em binário).

<CodeGroup>
  ```bash CLI theme={null}
  mka1 llm extract extract \
    --model meetkai:functionary-pt \
    --prompt 'Extraia o número da nota fiscal e o total.' \
    --schema '{
      "type": "object",
      "properties": {
        "invoice_number": { "type": "string" },
        "total_amount": { "type": "number" }
      },
      "required": ["invoice_number", "total_amount"]
    }' \
    --file ./invoice.pdf
  ```

  ```ts MKA1 SDK theme={null}
  const file = Bun.file('./invoice.pdf');

  const result = await mka1.llm.extract.extract({
    model: 'meetkai:functionary-pt',
    prompt: 'Extraia o número da nota fiscal e o total.',
    schema: {
      type: 'object',
      properties: {
        invoice_number: { type: 'string' },
        total_amount: { type: 'number' },
      },
      required: ['invoice_number', 'total_amount'],
    },
    file,
  });

  console.log(result.data);
  ```

  ```csharp C# SDK theme={null}
  using MeetKai.MKA1;
  using MeetKai.MKA1.Types.Requests;

  var sdk = new SDK(bearerAuth: "Bearer YOUR_API_KEY");

  var fileContent = await File.ReadAllBytesAsync("./invoice.pdf");

  var result = await sdk.Llm.Extract.ExtractAsync(new ExtractRequestBody()
  {
      Model = "meetkai:functionary-pt",
      Prompt = "Extraia o número da nota fiscal e o total.",
      Schema = Newtonsoft.Json.JsonConvert.SerializeObject(new Dictionary<string, object>()
      {
          { "type", "object" },
          { "properties", new Dictionary<string, object>()
              {
                  { "invoice_number", new Dictionary<string, object>() { { "type", "string" } } },
                  { "total_amount", new Dictionary<string, object>() { { "type", "number" } } },
              }
          },
          { "required", new List<object>() { "invoice_number", "total_amount" } },
      }),
      File = new ExtractFile()
      {
          FileName = "invoice.pdf",
          Content = fileContent,
      },
  });

  Console.WriteLine(result.ExtractionResponse?.Data);
  ```

  ```python Python SDK theme={null}
  import json

  result = sdk.llm.extract.extract(
      model="meetkai:functionary-pt",
      schema=json.dumps({
          "type": "object",
          "properties": {
              "invoice_number": {"type": "string"},
              "total_amount": {"type": "number"},
          },
          "required": ["invoice_number", "total_amount"],
      }),
      file={
          "file_name": "invoice.pdf",
          "content": open("./invoice.pdf", "rb"),
      },
  )

  print(result.data)
  ```

  ```bash bash theme={null}
  curl https://apigw.mka1.com/api/v1/llm/extract \
    --request POST \
    --header 'Content-Type: application/json' \
    --header 'Authorization: Bearer <mka1-api-key>' \
    --header 'X-On-Behalf-Of: <end-user-id>' \
    --data '{
      "model": "meetkai:functionary-pt",
      "prompt": "Extraia o número da nota fiscal e o total.",
      "schema": {
        "type": "object",
        "properties": {
          "invoice_number": {"type": "string"},
          "total_amount": {"type": "number"}
        },
        "required": ["invoice_number", "total_amount"]
      },
      "file": "(binary)"
    }'
  ```
</CodeGroup>

Use o fluxo de esquema reutilizável quando quiser um contrato estável entre vários arquivos.

## Gerenciar esquemas salvos

O recurso Extract também permite:

* Obter um esquema salvo pelo ID.
* Atualizar um esquema salvo.
* Excluir um esquema salvo.

Use esses endpoints quando seu contrato de extração mudar ao longo do tempo e você precisar manter o esquema sincronizado.
