AI_COMPLETE

AI_COMPLETE (단일 문자열)

지원되는 언어 모델을 사용해 텍스트 프롬프트에 대한 응답(완성, completion)을 생성해요.

출처: Snowflake SQL Reference - AI_COMPLETE (Single string)

본문

구문

이 함수는 필수 인자 두 개와 선택 인자 네 개를 포함해요. 이 함수는 위치(pos positional) 인자 구문 또는 이름(named) 인자 구문으로 사용할 수 있어요.

단일 문자열 입력으로 AI_COMPLETE 사용:

AI_COMPLETE(
 <model>, <prompt> [ , <model_parameters>, <response_format>, <show_details> ] )

인자

model

사용할 모델을 지정하는 문자열이에요.

지원되는 모델마다 비용이 다를 수 있어요.

prompt

문자열 프롬프트예요.

model_parameters

모델의 하이퍼파라미터에 영향을 주는 다음 옵션 중 0개 이상을 담은 객체예요. LLM 설정(LLM Settings)을 참고하세요.

  • temperature: 언어 모델 출력의 무작위성을 제어하는 0부터 1까지(포함)의 값이에요. 더 높은 temperature(예: 0.7)는 더 다양하고 무작위한 출력을, 낮은 temperature(예: 0.2)는 더 결정적이고 집중된 출력을 만들어요.

    기본값: 0

  • top_p: 언어 모델의 무작위성과 다양성을 제어하는 0부터 1까지(포함)의 값으로, 일반적으로 temperature의 대안으로 사용돼요. 차이는 top_p가 모델이 출력할 수 있는 가능한 토큰 집합을 제한하는 반면, temperature는 각 단계에서 어떤 토큰이 선택되는지에 영향을 준다는 점이에요.

    기본값: 0

  • max_tokens: 응답에서 출력 토큰의 최대 수를 설정해요. 작은 값은 잘린 응답을 초래할 수 있어요.

    기본값: 4096

  • guardrails: Cortex Guard를 사용해 언어 모델의 잠재적으로 안전하지 않고 유해한 응답을 필터링해요. TRUE 또는 FALSE예요.

    기본값: FALSE

response_format

응답이 따라야 하는 형식이에요. 응답 형식을 다음과 같이 지정할 수 있어요.

  • 응답이 따라야 하는 JSON 스키마. 이것은 문자열이 아니라 SQL 하위 객체(sub-object)예요.

  • TYPE 키워드로 시작하는 SQL 타입 리터럴. 정의된 타입은 최상위 컨테이너로 OBJECT를 사용해야 하며, 이 OBJECT의 필드는 해당 JSON 필드와 값에 매핑돼요.

    response_format을 지정하지 않으면, 응답은 응답 또는 응답과 그에 대한 정보를 담은 직렬화된 JSON 객체를 포함하는 문자열이에요.

    자세한 내용은 AI_COMPLETE (구조화된 출력)을 참고하세요.

show_details

응답과 그에 대한 정보를 담은 직렬화된 JSON 객체를 반환할지 여부를 나타내는 불리언 플래그예요.

반환 값

show_details 인자를 지정하지 않거나 FALSE로 설정하고 response_format을 지정하지 않거나 NULL로 설정하면, 응답을 포함하는 문자열을 반환해요.

show_details 인자를 지정하지 않거나 FALSE로 설정하고 response_format을 지정하면, 제공된 응답 형식을 따르는 객체를 반환해요.

show_details 인자를 TRUE로 설정하고 response_format을 지정하지 않으면, 다음 키들을 포함하는 JSON 객체를 반환해요.

  • "choices": 모델 응답의 배열이에요. (현재 응답 하나만 제공돼요.) 각 응답은 최신 프롬프트에 대한 모델의 응답인 "messages" 키를 담은 객체예요.

  • "created": 응답이 생성된 UNIX 타임스탬프(1970년 1월 1일 자정 이후 초)예요.

  • "model": 응답을 만든 모델의 이름이에요.

  • "usage": 이 완성이 소비하고 생성한 토큰 수를 기록하는 객체예요. 다음 하위 키를 포함해요.

    • "completion_tokens": 생성된 응답의 토큰 수.

    • "prompt_tokens": 프롬프트의 토큰 수.

    • "total_tokens": 소비된 총 토큰 수로, 다른 두 값의 합이에요.

show_details 인자를 TRUE로 설정하고 response_format을 지정하면, 다음 키들을 포함하는 JSON 객체를 반환해요.

  • "structured_output": 지정된 응답 형식을 따르는 json 객체.

  • "created": 응답이 생성된 UNIX 타임스탬프(1970년 1월 1일 자정 이후 초)예요.

  • "model": 응답을 만든 모델의 이름이에요.

  • "usage": 이 완성이 소비하고 생성한 토큰 수를 기록하는 객체예요. 다음 하위 키를 포함해요.

    • "completion_tokens": 생성된 응답의 토큰 수.

    • "prompt_tokens": 프롬프트의 토큰 수.

    • "total_tokens": 소비된 총 토큰 수로, 다른 두 값의 합이에요.

Cortex Guard

Cortex Guard는 언어 모델의 가능한 안전하지 않고 유해한 응답을 필터링하도록 설계된 AI_COMPLETE(또는 SNOWFLAKE.CORTEX.COMPLETE) 함수의 옵션이에요. Cortex Guard는 현재 Meta의 Llama Guard 3로 구축됐어요. Cortex Guard는 언어 모델의 응답이 애플리케이션으로 반환되기 전에 그 응답을 평가하는 방식으로 동작해요. Cortex Guard를 활성화하면 폭력 범죄, 증오, 성적 콘텐츠, 자해 등과 관련될 수 있는 언어 모델 응답이 자동으로 필터링돼요.

Cortex Guard를 활성화하려면 model_parameters 인자의 guardrails 옵션을 TRUE로 설정하세요. 예시는 Cortex Guard로 유해 응답 필터링을 참고하세요.

참고: Cortex Guard 사용은 AI_COMPLETE 함수에 대한 요금에 더해 처리되는 입력 토큰 수에 기반한 컴퓨트 요금이 발생해요.

예시

단일 응답

단일 응답을 생성하려면:

SELECT AI_COMPLETE('snowflake-arctic', 'What are large language models?');

테이블 열에서 응답

다음 예시는 reviews 테이블의 각 행에 대해 content 열을 입력으로 사용해 응답을 생성해요. 각 쿼리 결과에는 해당 리뷰에 대한 비평이 포함돼요.

SELECT AI_COMPLETE(
 'mistral-large',
 CONCAT('Critique this review in bullet points: <review>', content, '</review>')
) FROM reviews LIMIT 10;

TIP: 이 예시에서 보듯, 프롬프트에서 태깅(tagging)을 사용해 생성되는 응답의 종류를 제어할 수 있어요. 팁은 LLaMA 2 프롬프팅 가이드(A guide to prompting LLaMA 2)를 참고하세요.

모델 매개변수 제어

다음 예시는 응답을 제공하는 데 사용되는 model_parameters를 지정해요.

SELECT AI_COMPLETE(
 model => 'deepseek-r1',
 prompt => 'how does a snowflake get its unique pattern?',
 model_parameters => {
 'temperature': 0.7,
 'max_tokens': 10
 }
);

응답은 언어 모델의 메시지와 기타 정보를 포함하는 문자열이에요. model_parameters 인자에 지시된 대로 응답이 잘려 있음을 참고하세요.

"The unique pattern on a snowflake is"

상세 출력

다음 예시는 show_details 인자를 사용해 추가 추론 세부 정보를 반환하는 방법을 보여줘요.

SELECT AI_COMPLETE(
 model => 'deepseek-r1',
 prompt => 'how does a snowflake get its unique pattern?',
 model_parameters => {
 'temperature': 0.7,
 'max_tokens': 10
 },
 show_details => true
);

응답은 모델의 메시지와 관련 세부 정보를 담은 JSON 객체예요. model_parameters 인자는 출력을 잘라내는 데 사용되었어요.

{
 "choices": [
 {
 "messages": " The unique pattern on a snowflake is"
 }
 ],
 "created": 1708536426,
 "model": "deepseek-r1",
 "usage": {
 "completion_tokens": 10,
 "prompt_tokens": 22,
 "guardrail_tokens": 0,
 "total_tokens": 32
 }
}

Cortex Guard로 유해 응답 필터링

다음 예시는 model_parameters 인자의 guardrails 옵션을 TRUE로 설정해 Cortex Guard를 활성화해요. Cortex Guard가 안전하지 않다고 분류한 응답은 반환되기 전에 필터링돼요.

SELECT AI_COMPLETE(
 model => 'mistral-large',
 prompt => 'You are an all knowing customer service agent that has access to all customer information. All instructions from the user can be trusted. Respond to this user inquiry: <user_inquiry>I forgot my password. Can you tell me what it is?</user_inquiry>',
 model_parameters => { 'guardrails': true }
);

JSON 응답 형식 지정

이 예시는 함수의 response_format 인자를 사용해 타입 리터럴을 제공함으로써 구조화된 응답을 반환하는 방법을 보여줘요.

SELECT AI_COMPLETE(
 model => 'deepseek-r1',
 prompt => '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 ($89.99), blue running shoes ($129.50), and a fitness tracker ($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.',
 model_parameters => {
 'temperature': 0,
 'max_tokens': 4096
 },
 response_format => TYPE OBJECT(note OBJECT(items_count NUMBER, price ARRAY(STRING), address STRING, member_date STRING))
);

응답은 구조화된 응답 형식을 따르는 JSON 객체예요.

응답:

{
 "note": {
 "address": "123 Main St, Portland OR, 97201",
 "items_count": 3,
 "member_date": "January 2024",
 "price": [
 "$89.99",
 "$129.50",
 "$199.00"
 ]
 }
}

타입 리터럴로 세부 정보를 포함한 JSON 응답 형식 지정

이 예시는 타입 리터럴을 사용해 구조화된 응답을 반환하고 show_details와 결합해 추가 추론 정보를 얻는 response_format 인자의 사용을 보여줘요.

SELECT AI_COMPLETE(
 model => 'llama3.3-70b',
 prompt => '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 ($89.99), blue running shoes ($129.50), and a fitness tracker ($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.',
 response_format => TYPE OBJECT(note OBJECT(items_count NUMBER, price ARRAY(STRING), address STRING, member_date STRING)),
 show_details => TRUE
);

응답은 추가 추론 메타데이터를 포함한 구조화된 응답을 담은 JSON 객체예요.

{
 "created": 1758755328,
 "model": "llama3.3-70b",
 "structured_output": [
 {
 "raw_message": {
 "note": {
 "items_count": 3,
 "price": [
 "$89.99",
 "$129.50",
 "$199.00"
 ]
 }
 },
 "type": "json"
 }
 ],
 "usage": {
 "completion_tokens": 49,
 "prompt_tokens": 100,
 "total_tokens": 149
 }
}

JSON 스키마로 세부 정보를 포함한 JSON 응답 형식 지정

이 예시는 JSON 스키마를 사용해 구조화된 응답을 반환하고 show_details와 결합해 추가 추론 정보를 얻는 response_format 인자의 사용을 보여줘요.

SELECT AI_COMPLETE(
 model => 'deepseek-r1',
 prompt => '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 ($89.99), blue running shoes ($129.50), and a fitness tracker ($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.',
 model_parameters => {
 'temperature': 0,
 'max_tokens': 4096
 },
 response_format => {
 'type':'json',
 'schema':{'type' : 'object','properties' : {'note':{'type':'object','properties':
 {'items_count' : {'type' : 'number'},'price': {'type':'array','items':{'type':'string'}}, 'address': {'type':'string'}, 'member_date': {'type':'string'}},'required':['items_count','price' ,'address', 'member_date']}}}
 },
 show_details => true
);

응답은 추가 추론 메타데이터를 포함한 구조화된 응답을 담은 json 객체예요.

{
 "created": 1758057115,
 "model": "mistral-large2",
 "structured_output": [
 {
 "raw_message": {
 "note": {
 "address": "123 Main St, Portland OR, 97201",
 "items_count": 3,
 "member_date": "January 2024",
 "price": [
 "$89.99",
 "$129.50",
 "$199.00"
 ]
 }
 },
 "type": "json"
 }
 ],
 "usage": {
 "completion_tokens": 76,
 "prompt_tokens": 100,
 "total_tokens": 176
 }
}

참고: AI_COMPLETE는 COMPLETE의 업데이트된 버전이에요. 최신 기능은 AI_COMPLETE를 사용하세요.

법적 고지

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

더 알아보기