Categorias:

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

AI_COUNT_TOKENS

Nota

AI_COUNT_TOKENS é a versão atualizada do COUNT_TOKENS (SNOWFLAKE.CORTEX). Para obter a funcionalidade mais recente, use AI_COUNT_TOKENS.

Retorna o número estimado de tokens em um prompt para o modelo de linguagem grande especificado ou a função específica da tarefa. Para funções que podem receber entradas adicionais que afetam a contagem de tokens, como nome do modelo ou categorias/rótulos, essas entradas também podem ser especificadas.

Sintaxe

A sintaxe pode variar de acordo com a função utilizada. Em geral, você passa o nome da função, o nome do modelo, se aplicável, o texto de entrada e quaisquer opções adicionais que afetem a contagem de tokens.

AI_COUNT_TOKENS(<function_name>, <input_text> )
AI_COUNT_TOKENS( <function_name>, <model_name> , <input_text> )
AI_COUNT_TOKENS( <function_name>, <input_text>, <options> )
AI_COUNT_TOKENS( <function_name>, <model_name>, <input_text>, <options> )
Copy

AI_COUNT_TOKENS usa variações de sintaxe específicas para algumas funções. Por exemplo:

AI_COUNT_TOKENS( 'ai_similarity', <input_text_1>, <input_text_2>, <options> )
AI_COUNT_TOKENS( 'ai_classify', <input_text>, <categories> )
AI_COUNT_TOKENS( 'ai_translate', <input_text>, <source_language>, <target_language> )
Copy

Consulte Exemplos para ver padrões de uso específicos da função.

Argumentos

Obrigatório:

function_name

Cadeia de caracteres contendo o nome da função na qual você deseja basear a contagem de tokens, como 'ai_complete' ou 'ai_sentiment'. O nome da função deve começar com «ai_» e usar apenas letras minúsculas.

Uma lista completa de funções aceitas está disponível na tabela Disponibilidade regional.

input_text ou input_text_1, input_text_2

Insira o texto para contar os tokens.

Opcional:

model_name

Cadeia de caracteres contendo o nome do modelo no qual você deseja basear o conteúdo do token. Obrigatório se a função especificada por function_name exigir que você escolha o modelo a ser utilizado, como AI_COMPLETE ou AI_EMBED.

A list of available LLM models is available in the Disponibilidade regional table. However, not all models are currently supported. Snowflake intends to add support for additional models over time.

Para AI_COMPLETE, os seguintes modelos não são aceitos:

  • claude-4-opus

  • claude-4-sonnet

  • claude-3-7-sonnet

  • claude-3-5-sonnet

  • openai-gpt-4.1

  • openai-o4-mini

categories

Uma matriz de valores VARIANT que especifica uma ou mais categorias ou rótulos a serem utilizados, para funções que exigem esses dados. As categorias são incluídas na contagem de tokens de entrada.

options

VARIANT que especifica opções adicionais que afetam como a função processa a entrada. Para funções que usam duas entradas de texto, como AI_SIMILARITY, as opções são usadas para especificar o modelo.

Retornos

Um valor INTEGER que é o número de tokens de texto de entrada calculado usando os valores de parâmetro fornecidos.

Notas de uso

  • Although function names are usually written in all uppercase, use only lowercase letters in function and model names.

  • COUNT_TOKENS does not work with LLM functions in the SNOWFLAKE.CORTEX namespace or with fine-tuned models. You must specify a function name that begins with «ai_».

  • COUNT_TOKENS accepts only text, not image, audio, or video inputs.

  • COUNT_TOKENS incorre apenas em custos de computação e não gera cobranças com base na contagem de tokens.

  • COUNT_TOKENS está disponível em todas as regiões, mesmo para modelos indisponíveis em uma determinada região.

Exemplos

Exemplo de AI_COMPLETE

A instrução SQL a seguir conta o número de tokens em um prompt para AI_COMPLETE e o modelo llama3.3-70b:

SELECT AI_COUNT_TOKENS('ai_complete', 'llama3.3-70b', 'Summarize the insights from this
call transcript in 20 words: "I finally splurged on these after months of hesitation about
the price, and I\'m mostly impressed. The Nulu fabric really is as buttery-soft as everyone says,
and they\'re incredibly comfortable for yoga and lounging. The high-rise waistband stays put
and doesn\'t dig in, which is rare for me. However, I\'m already seeing some pilling after
just a few wears, and they definitely require gentle care. They\'re also quite delicate -
I snagged them slightly on my gym bag zipper. Great for low-impact activities, but I wouldn\'t
recommend for high-intensity workouts. Worth it for the comfort factor"');
Copy

Resposta:

158

Exemplo de AI_EMBED

A instrução SQL a seguir conta o número de tokens no texto que está sendo incorporado usando a função AI_EMBED e o modelo nv-embed-qa-4':

SELECT AI_COUNT_TOKENS('ai_embed', 'nv-embed-qa-4', '"I finally splurged on these after months
of hesitation about the price, and I\'m mostly impressed. The Nulu fabric really is as buttery-soft
as everyone says, and they\'re incredibly comfortable for yoga and lounging. The high-rise waistband
stays put and doesn\'t dig in, which is rare for me. However, I\'m already seeing some pilling after
just a few wears, and they definitely require gentle care. They\'re also quite delicate - I snagged
them slightly on my gym bag zipper. Great for low-impact activities, but I wouldn\'t recommend for
high-intensity workouts. Worth it for the comfort factor"');
Copy

Resposta:

142

Exemplos AI_CLASSIFY

Este exemplo calcula o número total de tokens de entrada necessários para a classificação de texto com a entrada e os rótulos fornecidos:

SELECT AI_COUNT_TOKENS('ai_classify',
  'One day I will see the world and learn to cook my favorite dishes',
  [
      {'label': 'travel'},
      {'label': 'cooking'},
      {'label': 'reading'},
      {'label': 'driving'}
  ]
);
Copy

Resposta:

187

O exemplo a seguir adiciona descrições por rótulo e uma descrição geral da tarefa ao exemplo anterior:

SELECT AI_COUNT_TOKENS('ai_classify',
  'One day I will see the world and learn to cook my favorite dishes',
  [
    {'label': 'travel', 'description': 'content related to traveling'},
    {'label': 'cooking','description': 'content related to food preparation'},
    {'label': 'reading','description': 'content related to reading'},
    {'label': 'driving','description': 'content related to driving a car'}
  ],
  {
    'task_description': 'Determine topics related to the given text'
  };
Copy

Resposta:

254

O exemplo a seguir se baseia nos dois exemplos anteriores, adicionando exemplos de rótulos:

SELECT AI_COUNT_TOKENS('ai_classify',
  'One day I will see the world and learn to cook my favorite dishes',
  [
    {'label': 'travel', 'description': 'content related to traveling'},
    {'label': 'cooking','description': 'content related to food preparation'},
    {'label': 'reading','description': 'content related to reading'},
    {'label': 'driving','description': 'content related to driving a car'}
  ],
  {
    'task_description': 'Determine topics related to the given text',
    'examples': [
      {
        'input': 'i love traveling with a good book',
        'labels': ['travel', 'reading'],
        'explanation': 'the text mentions traveling and a good book which relates to reading'
      }
    ]
  }
);
Copy

Resposta:

298

Exemplos AI_SENTIMENT

A instrução SQL a seguir conta o número de tokens no texto que está sendo analisado em busca de sentimento usando a função AI_SENTIMENT:

SELECT AI_COUNT_TOKENS('ai_sentiment',
  'This place makes the best truffle pizza in the world! Too bad I cannot afford it');
Copy

Resposta:

139

O exemplo a seguir adiciona rótulos ao exemplo anterior:

SELECT AI_COUNT_TOKENS('ai_sentiment',
  'This place makes the best truffle pizza in the world! Too bad I cannot afford it',
  [
    {'label': 'positive'},
    {'label': 'negative'},
    {'label': 'neutral'}
  ]
);
Copy

Resposta:

148

AI_SIMILARITY examples

The following SQL statement counts the number of tokens in an AI_SIMILARITY call that uses the default model.

SELECT AI_COUNT_TOKENS('ai_similarity',
  'The plot is fast and the characters feel real. This book kept me awake all night
  because the mystery is so deep. I love how the author  handles the ending. It is a
  great read for anyone who likes suspense.',
  'The story is quick and the people feel true. This novel kept me awake all night
  because the puzzle is so big. I love how the writer handles the finale. It is a
  solid choice for anyone who enjoys suspense.');
Copy

Resposta:

101

The following SQL statement counts the number of tokens in an AI_SIMILARITY that uses the e5-base-v2 model:

SELECT AI_COUNT_TOKENS('ai_similarity',
  'The plot is fast and the characters feel real. This book kept me awake all night
  because the mystery is so deep. I love how the author handles the ending. It is a
  great read for anyone who likes suspense.',
  'The story is quick and the people feel true. This novel kept me awake all night
  because the puzzle is so big. I love how the writer handles the finale. It is a
  solid choice for anyone who enjoys suspense.', {'model': 'e5-base-v2'})
Copy

Resposta:

92

AI_TRANSLATE example

The following SQL statement counts the number of tokens used by AI_TRANSLATE when translating text from English to German.

SELECT AI_COUNT_TOKENS('ai_translate',
  'The plot is fast and the characters feel real. This book kept me awake all night
  because the mystery is so deep. I love how the author handles the ending. It is a
  great read for anyone who likes suspense.', 'en', 'de');
Copy

Resposta:

51