AI_COUNT_TOKENS

AI_COUNT_TOKENS

AI_COUNT_TOKENS() 함수는 지정된 대형 언어 모델 또는 작업별 함수에 대한 프롬프트의 입력 토큰 수 추정값을 반환해요. 모델 이름이나 범주/레이블처럼 입력 토큰 수에 영향을 줄 수 있는 추가 입력을 받는 함수의 경우, 그 입력도 지정할 수 있어요.

출처: Snowflake SQL Reference

본문

문법

문법은 사용되는 함수에 따라 달라질 수 있어요. 일반적으로 함수 이름, 해당한다면 모델 이름, 입력 텍스트, 토큰 수에 영향을 주는 추가 옵션을 전달해요.

AI_COUNT_TOKENS( <function_name>, <input_text> [, <return_error_details> ] )
AI_COUNT_TOKENS( <function_name>, <model_name>, <input_text> [, <return_error_details> ] )
AI_COUNT_TOKENS( <function_name>, <input_text>, <options> [, <return_error_details> ] )
AI_COUNT_TOKENS( <function_name>, <model_name>, <input_text>, <options> [, <return_error_details> ] )

AI_COUNT_TOKENS는 일부 함수에 대해 특정 문법 변형을 사용해요. 예:

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

함수별 사용 패턴은 Examples 참고.

인자

function_name (필수) — 토큰 수를 계산할 기준이 되는 함수 이름을 담은 문자열, 예: 'ai_complete' 또는 'ai_sentiment'. 함수 이름은 "ai_"로 시작하고 소문자만 사용해야 해요. 지원되는 함수의 전체 목록은 Regional availability 표에서 볼 수 있어요.

input_text (필수) — 토큰을 계산할 입력 텍스트예요.

model_name (선택) — 토큰 내용을 계산할 기준이 되는 모델 이름을 담은 문자열이에요. function_name이 지정한 함수가 AI_COMPLETE나 AI_EMBED처럼 사용할 모델을 선택하도록 요구하면 필요해요. 사용 가능한 LLM 모델 목록은 Regional availability 표에서 볼 수 있어요. Snowflake는 시간이 지나며 추가 모델에 대한 지원을 추가하려 해요.

categories (선택) — 이 데이터가 필요한 함수에 대해 하나 이상의 범주 또는 레이블을 지정하는 VARIANT 값 배열이에요. 범주는 입력 토큰 수에 포함돼요.

options (선택) — 함수가 입력을 처리하는 방식에 영향을 주는 추가 옵션을 지정하는 VARIANT예요. AI_SIMILARITY처럼 두 텍스트 입력을 받는 함수의 경우 options는 모델을 지정하는 데 사용돼요.

return_error_details (선택) — 오류 발생 시 오류 세부 정보를 반환할지 나타내는 BOOLEAN 플래그예요. TRUE로 설정하면 함수는 값과 오류 메시지를 담은 OBJECT를 반환하는데, 함수의 성공/실패 여부에 따라 둘 중 하나는 NULL이에요. 자세한 내용은 Error behavior 참고.

반환

제공한 입력 텍스트와 다른 파라미터 값에 대한 입력 토큰의 추정 수인 INTEGER 값을 반환해요. 이 값은 출력(생성된) 토큰은 포함하지 않아요.

오류 동작 (Error behavior)

기본적으로 AI_COUNT_TOKENS가 입력을 처리할 수 없으면 함수는 NULL을 반환해요. 쿼리가 여러 행을 처리하면 오류가 있는 행은 NULL을 반환하고 쿼리가 완료되는 것을 막지 않아요.

오류 시 반환 값은 return_error_details 인자에 따라 달라져요. 다음 표는 return_error_details 인자에 따른 반환 값을 보여줘요.

return_error_details 반환 값 설명
FALSE / 전달 안 함 NULL
TRUE value와 error 필드를 가진 OBJECT value: 토큰 수인 INTEGER 값, 오류가 발생했으면 NULL. error: 오류가 발생했으면 오류 메시지를 담은 VARCHAR, 함수가 성공하면 NULL.

AI 함수의 오류 처리에 대한 자세한 내용은 Snowflake Cortex AI Function: Multirow error handling improvements 문서를 참고하세요.

사용 노트

  • 함수 이름은 보통 대문자로 쓰지만, 함수와 모델 이름에는 소문자만 사용하세요.
  • AI_COUNT_TOKENS는 SNOWFLAKE.CORTEX 네임스페이스의 LLM 함수나 파인튜닝된 모델에서는 동작하지 않아요. "ai_"로 시작하는 함수 이름을 지정해야 해요.
  • AI_COUNT_TOKENS는 텍스트만 받아들여요. 이미지, 오디오, 비디오 입력은 받지 않아요.
  • AI_COUNT_TOKENS는 입력 토큰만 추정해요. 청구에도 기여하는 출력(생성된) 토큰은 추정하지 않아요. 쿼리에 대한 실제 청구된 입력·출력 토큰을 보려면 CORTEX_FUNCTIONS_QUERY_USAGE_HISTORY 뷰를 사용하세요.
  • 토큰 수의 정확도는 모델에 따라 달라져요. 자세한 내용은 Token count accuracy 참고.
  • Anthropic Claude 모델에서 AI_COMPLETE를 response_format 인자(구조화 출력)와 함께 사용하면 구조화 출력을 지원하기 위해 추가 요청 콘텐츠가 생성돼요. 이 콘텐츠는 청구된 입력 토큰에 포함되지만 AI_COUNT_TOKENS 추정에는 반영되지 않아요. 결과적으로 이 요청들의 청구된 입력 토큰 수는 추정 토큰 수보다 실질적으로 더 높을 수 있어요.
  • AI_COUNT_TOKENS는 컴퓨팅 비용만 발생하며 토큰 수에 따라 청구하지 않아요.
  • AI_COUNT_TOKENS는 모델이 해당 지역에서 사용 가능하지 않아도 모든 지역에서 사용할 수 있어요.

토큰 수 정확도 (Token count accuracy)

토큰 수의 정확도는 모델에 따라 달라져요. 대부분의 모델에서 AI_COUNT_TOKENS는 정확한 개수를 반환해요. 다음 표는 모델별 예상 정확도를 보여줘요.

모델 토큰 수 정확도
Anthropic Claude 추정값; 상대 오차 3% 미만
Google Gemini 추정값; 상대 오차 3% 미만
OpenAI 거의 정확
기타 모든 모델 정확

참고: 구조화 출력(response_format 인자, Anthropic Claude 모델에서 지원)을 사용하면 추정값과 청구된 입력 토큰 수의 차이가 여기 표시된 값보다 훨씬 커질 수 있어요. 자세한 내용은 Usage notes의 구조화 출력 참고를 보세요.

예제

AI_COMPLETE 예제

다음 SQL 문은 AI_COMPLETE와 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"');

응답:

158

구조화 출력이 있는 AI_COMPLETE 예제

다음 SQL 문은 Anthropic Claude 모델에서 response_format 인자(구조화 출력)를 사용하는 AI_COMPLETE 호출의 입력 토큰을 추정해요:

SELECT AI_COUNT_TOKENS(
  'ai_complete',
  'claude-sonnet-4-5',
  'Extract structured data from this customer interaction note: Customer Sarah Jones
  complained about the mobile app crashing during checkout. She tried to purchase 3 items:
  a red XL jacket (EUR 89.99), blue running shoes (EUR 129.50), and a fitness tracker
  (EUR 199.00). The app crashed after she entered her shipping address at 123 Main St,
  Portland OR, 97201. She has been a premium member since January 2024.',
  {
    'type': 'json',
    'schema': {
      'type': 'object',
      'properties': {
        'items_count': {'type': 'number'},
        'prices': {'type': 'array', 'items': {'type': 'string'}},
        'address': {'type': 'string'},
        'member_date': {'type': 'string'}
      },
      'required': ['items_count', 'prices', 'address', 'member_date']
    }
  }
);

응답:

296

참고: Claude 모델의 구조화 출력은 입력 토큰으로 청구되는 추가 요청 콘텐츠를 생성하지만 이 추정에는 반영되지 않으므로, 청구된 입력 토큰 수가 추정 토큰 수보다 실질적으로 더 높을 수 있어요. 자세한 내용은 Usage notes 참고.

AI_EMBED 예제

다음 SQL 문은 AI_EMBED 함수와 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"');

응답:

142

AI_CLASSIFY 예제

이 예제는 주어진 입력과 레이블로 텍스트 분류에 필요한 총 입력 토큰 수를 계산해요:

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'}
  ]
);

응답:

187

다음 예제는 이전 예제에 레이블별 설명과 전체 작업 설명을 추가해요:

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'
  }
);

응답:

254

다음 예제는 이전 두 예제에 레이블 예제를 추가해 확장해요:

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'
      }
    ]
  }
);

응답:

298

AI_SENTIMENT 예제

다음 SQL 문은 AI_SENTIMENT 함수로 감성을 분석하는 텍스트의 토큰 수를 계산해요:

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

응답:

139

다음 예제는 이전 예제에 레이블을 추가해요:

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'}
  ]
);

응답:

148

AI_SIMILARITY 예제

다음 SQL 문은 기본 모델을 사용하는 AI_SIMILARITY 호출의 토큰 수를 계산해요.

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.');

응답:

101

다음 SQL 문은 e5-base-v2 모델을 사용하는 AI_SIMILARITY의 토큰 수를 계산해요:

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'});

응답:

92

AI_TRANSLATE 예제

다음 SQL 문은 텍스트를 영어에서 독일어로 번역할 때 AI_TRANSLATE가 사용하는 토큰 수를 계산해요.

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');

응답:

51

AI_REDACT 예제

다음 SQL 문은 기본 AI_REDACT 요청의 입력 토큰 수를 계산해요:

SELECT AI_COUNT_TOKENS('ai_redact',
  'My name is John Smith and I live at twenty third street, San Francisco.');

응답:

442

다음 예제는 이름과 이메일 주소만 편집할 때 토큰을 추정하기 위한 categories 인자를 포함해요:

SELECT AI_COUNT_TOKENS('ai_redact',
  'My name is John and I live at twenty third street, San Francisco.',
  ['NAME', 'EMAIL']);

응답:

441

참고: AI_COUNT_TOKENS는 COUNT_TOKENS의 갱신된 버전이에요. 최신 기능을 사용하려면 AI_COUNT_TOKENS를 사용하세요.

법적 고지

법적 고지는 Snowflake AI and ML을 참고하세요.

더 알아보기 (Learn more)