Categorias:

Funções de cadeia de caracteres e binários (funções de AI)

AI_EXTRACT

Extrai informações de uma string ou arquivo de entrada.

Sintaxe

Extrair informações de uma string de entrada:

AI_EXTRACT( <text>, <responseFormat> )
Copy
AI_EXTRACT( text => <text>,
            responseFormat => <responseFormat> )
Copy

Extrair informações de um arquivo:

AI_EXTRACT( <file>, <responseFormat> )
Copy
AI_EXTRACT( file => <file>,
            responseFormat => <responseFormat> )
Copy

Argumentos

text

Uma string de entrada para extração.

file

Um FILE para extração.

Formatos de arquivo compatíveis:

  • PDF

  • PNG

  • PPTX, PPT

  • EML

  • DOC, DOCX

  • JPEG, JPG

  • HTM, HTML

  • TEXT, TXT

  • TIF, TIFF

  • BMP, GIF, WEBP

  • MD

Os arquivos devem ter menos de 100 MB de tamanho.

responseFormat

Informações a serem extraídas em um dos seguintes formatos de resposta:

  • Simple object schema that maps the label and information to be extracted; for example:

    {'name': 'What is the last name of the employee?', 'address': 'What is the address of the employee?'}
    
  • Uma matriz de strings com as informações a serem extraídas, por exemplo:

    ['What is the last name of the employee?', 'What is the address of the employee?']
    
  • An array of arrays that contain two strings (label and the information to be extracted); for example:

    [['name', 'What is the last name of the employee?'], ['address', 'What is the address of the employee?']]
    
  • A JSON schema that defines the structure of the extracted information. Supports entity and table extraction. For example:

    {
      'schema': {
        'type': 'object',
        'properties': {
          'income_table': {
            'description': 'Income for FY2026Q2',
            'type': 'object',
            'column_ordering': ['month', 'income'],
            'properties': {
              'month': {
                'description': 'Month',
                'type': 'array'
              },
              'income': {
                'description': 'Income',
                'type': 'array'
              }
            }
          },
          'title': {
            'description': 'What is the title of the document?',
            'type': 'string'
          },
          'employees': {
            'description': 'What are the names of employees?',
            'type': 'array'
          }
        }
      }
    }
    

    Nota

    • Você não pode combinar o JSON Formato de esquema com outros formatos de resposta. Se responseFormat contém o schema Chave, você deve definir todas as perguntas dentro da JSON esquema. Chaves adicionais não são suportadas.

    • O modelo aceita apenas certas formas de JSON esquema. O tipo de nível superior deve ser sempre um objeto, que contém subobjetos extraídos independentemente. Os subobjetos podem ser uma tabela (objeto de listas de strings que representam colunas), uma lista de strings ou uma string.

      O único tipo escalar compatível atualmente é a string.

    • O campo description é opcional.

      Use a description campo para fornecer contexto ao modelo; por exemplo, para ajudar o modelo a localizar a tabela correta em um documento.

    • Use o campo column_ordering para especificar a ordem de todas as colunas na tabela extraída. O campo column_ordering diferencia maiúsculas de minúsculas e deve corresponder aos nomes das colunas definidos no campo properties.

Retornos

Um objeto JSON contendo as informações extraídas.

Exemplo de uma saída que inclui matriz, tabela e extração de valor único:

{
  "error": null,
  "response": {
    "employees": [
      "Smith",
      "Johnson",
      "Doe"
    ],
    "income_table": {
      "income": ["$120 678","$130 123","$150 998"],
      "month": ["February", "March", "April"]
    },
    "title": "Financial report"
  }
}

Requisitos de controle de acesso

Users must use a role that has been granted the SNOWFLAKE.CORTEX_USER database role. For information about granting this privilege, see Cortex LLM privileges.

Notas de uso

  • Você não pode usar os dois text e file Parâmetros simultaneamente na mesma chamada de função.

  • You can either ask questions in natural language or describe information to be extracted (such as city, street, ZIP code); for example:

    ['address': 'City, street, ZIP', 'name': 'First and last name']
    
  • Os seguintes idiomas são compatíveis:

    • Árabe

    • Bengali

    • Birmanês

    • Cebuano

    • Chinês

    • Tcheco

    • Holandês

    • Inglês

    • Francês

    • Alemão

    • Hebraico

    • Hindi

    • Indonésio

    • Italiano

    • Japonês

    • Quemer

    • Coreano

    • Lao

    • Malaio

    • Persa

    • Polonês

    • Português

    • Russo

    • Espanhol

    • Tagalo

    • Tailandês

    • Turco

    • Urdu

    • Vietnamita

  • Os documentos não devem ter mais de 125 páginas.

  • Em uma única chamada AI_EXTRACT, você pode fazer no máximo 100 perguntas para extração de entidade e um máximo de 10 perguntas para extração de tabela.

    Uma pergunta de extração de tabela é igual a 10 perguntas de extração de entidade. Por exemplo, você pode fazer 4 perguntas de extração de tabela e 60 perguntas de extração de entidade em um único AI_EXTRACT chamar.

  • O comprimento máximo de saída para extração de entidade é de 512 tokens por pergunta. Para extração de tabela, o modelo retorna respostas com um máximo de 4096 tokens.

  • Client-side encrypted stages are not supported.

  • Não há suporte para pontuações de confiança.

Exemplos

Extraction from an input string

  • Este exemplo extrai informações do texto de entrada:

    SELECT AI_EXTRACT(
      text => 'John Smith lives in San Francisco and works for Snowflake',
      responseFormat => {'name': 'What is the first name of the employee?', 'city': 'What is the address of the employee?'}
    );
    
    Copy
  • Este exemplo extrai e analisa informações do texto de entrada:

    SELECT AI_EXTRACT(
      text => 'John Smith lives in San Francisco and works for Snowflake',
      responseFormat => PARSE_JSON('{"name": "What is the first name of the employee?", "address": "What is the address of the employee?"}')
    );
    
    Copy

Extraction from a file

  • Este exemplo extrai informações do arquivo document.pdf:

    SELECT AI_EXTRACT(
      file => TO_FILE('@db.schema.files','document.pdf'),
      responseFormat => [['name', 'What is the first name of the employee?'], ['city', 'Where does the employee live?']]
    );
    
    Copy
  • The following example extracts information from all files in a directory on a stage:

    Nota

    Certifique-se de que a tabela de diretórios esteja habilitada. Para obter mais informações, consulte Gerenciamento de tabelas de diretório.

    SELECT AI_EXTRACT(
      file => TO_FILE('@db.schema.files', relative_path),
      responseFormat => [
        'What is this document?',
        'How would you classify this document?'
      ]
    ) FROM DIRECTORY (@db.schema.files);
    
    Copy
  • The following example extracts the title value from the report.pdf file:

    SELECT AI_EXTRACT(
      file => TO_FILE('@db.schema.files', 'report.pdf'),
      responseFormat => {
        'schema': {
          'type': 'object',
          'properties': {
            'title': {
              'description': 'What is the title of document?',
              'type': 'string'
            }
          }
        }
      }
    );
    
    Copy
  • The following example extracts the employees array from the report.pdf file:

    SELECT AI_EXTRACT(
      file => TO_FILE('@db.schema.files', 'report.pdf'),
      responseFormat => {
        'schema': {
          'type': 'object',
          'properties': {
            'employees': {
              'description': 'What are the surnames of employees?',
              'type': 'array'
            }
          }
        }
      }
    );
    
    Copy
  • The following example extracts the income_table table from the report.pdf file:

    SELECT AI_EXTRACT(
      file => TO_FILE('@db.schema.files', 'report.pdf'),
      responseFormat => {
        'schema': {
          'type': 'object',
          'properties': {
            'income_table': {
              'description': 'Income for FY2026Q2',
              'type': 'object',
              'column_ordering': ['month', 'income'],
              'properties': {
                'month': {
                  'type': 'array'
                },
                'income': {
                  'type': 'array'
                }
              }
            }
          }
        }
      }
    );
    
    Copy
  • The following example extracts table (income_table), single value (title), and array (employees) from the report.pdf file:

    SELECT AI_EXTRACT(
      file => TO_FILE('@db.schema.files', 'report.pdf'),
      responseFormat => {
        'schema': {
          'type': 'object',
          'properties': {
            'income_table': {
              'description': 'Income for FY2026Q2',
              'type': 'object',
              'column_ordering': ['month', 'income'],
              'properties': {
                'month': {
                  'type': 'array'
                },
                'income': {
                  'type': 'array'
                }
              }
            },
            'title': {
              'description': 'What is the title of document?',
              'type': 'string'
            },
            'employees': {
              'description': 'What are the surnames of employees?',
              'type': 'array'
            }
          }
        }
      }
    );
    
    Copy

Disponibilidade regional

Consulte Disponibilidade regional.