다단계 AI 워크플로 설계

Snowflake에서 시작하는 생성형 AI

James Cha-Earley

Senior Developer Advocate, Snowflake

Cortex 리뷰 워크플로

목표: 글로벌 고객 피드백 자동화 시스템 구축

$$

  • 각 리뷰를 영어로 번역
  • 핵심 요지 요약
  • 적절한 팀 분류 및 라우팅
  • 대응 문안 생성
  • 원문 언어로 재번역

리뷰 수신 후 번역, 요약·분류를 거쳐 응답을 전송하는 워크플로

Snowflake에서 시작하는 생성형 AI

리뷰 추출

-- SQL cell
SELECT DESCRIPTION
FROM HOTELS.REVIEWS
WHERE LANGUAGE = 'es'
LIMIT 1;
# Python cell
df = cell1.to_pandas()
review_text = df["DECRIPTION"].iloc[0]
Snowflake에서 시작하는 생성형 AI

스페인어 리뷰

print(review_text)
Buen hotel y bien situado pero desafortunadamente no me toco buena suerte con 
el servicio; el aire no servía; pedí la cama extra tres veces; la cafetera estaba
dañada; y me sacaron las maletas fuera porque argumentaron que no hice Check out;
siendo que era un día despues; pero su sistema lo marco antes; una total
descortesía hecharme del cuarto y cancelar mis llaves; regresar de caminar y darse
cuenta que han tomado tus cosas fuera es increíble y mas aun sin ninguna disculpa;
yo no volvería ahí aunque la vrd el hotel es bueno y su jubilación el trato
me decepciono
Snowflake에서 시작하는 생성형 AI

번역

translated = translate(
    text=review_text,
    from_language="es",
    to_language="en"
)

print(translated)
Good hotel and well located, but unfortunately, I didn't have good luck with the service; the air
conditioning didn't work; I asked for the extra bed three times; the coffee maker was broken; 
and they took my bags out because they argued that I hadn't checked out; even though it was a day
later; but their system marked it as checked out; a total discourtesy to throw me out of the room
and cancel my keys; returning from a walk and realizing they've taken your things out is
incredible and even more so without any apology; I wouldn't go back there even though the hotel
itself is good and their retirement the treatment disappoints me.
Snowflake에서 시작하는 생성형 AI

요약

summary = summarize(text=translated)

print(summary)
호텔 위치는 좋았지만 서비스가 실망스러웠습니다. 에어컨이 작동하지 않았고,
여러 번 요청했지만 추가 침대가 제공되지 않았으며, 커피 메이커도 고장 나 있었습니다.
직원들은 늦은 체크아웃이었음에도 짐을 밖으로 옮기고 키를 취소해 무례했고,
그로 인해 매우 실망스러웠습니다.
Snowflake에서 시작하는 생성형 AI

분류

topic = classify_text(
    text=summary,
    labels=["staff", "cleanliness", "pricing", "room", "food"]
)

print(topic)
{
  "label": "staff"
}
Snowflake에서 시작하는 생성형 AI

텍스트 생성

response = complete(
        prompt=f"Write a brief and professional response to this review: {summary}",
        model='llama3.1-8b',
        options={'temperature':0.3, 'max_tokens':120})

print(response)
피드백을 공유해 주셔서 감사합니다. 위치가 편리했다니 다행이지만,
서비스 문제로 불편을 겪으신 점 진심으로 사과드립니다.
머무시는 동안 여러 불편이 겹쳐 얼마나 답답하셨을지 이해합니다.
말씀해 주신 사항은 재발 방지를 위해 관련 팀과 공유했습니다.
Snowflake에서 시작하는 생성형 AI

응답 번역

translated_response = translate(
    text=response,
    from_language="en",
    to_language="es"
)

print(translated_response)
Gracias por compartir sus comentarios. Si bien nos alegra saber que encontró conveniente
la ubicación, lamentamos sinceramente los inconvenientes que experimentó con el servicio.
Entendemos lo frustrante que debió haber sido enfrentar múltiples inconvenientes durante
su estadía. Sus comentarios han sido compartidos con el equipo para asegurarnos de que
estas situaciones se aborden y no vuelvan a ocurrir.
Snowflake에서 시작하는 생성형 AI

Cortex 비용 모델

입력 토큰, 연산, 출력 토큰 각각에 비용이 발생하는 코텍스 워크플로

1 Image generated by ChatGPT-4o
Snowflake에서 시작하는 생성형 AI

비용 절감 방법

$$

  • 입력 정제, 관련 텍스트만 처리

  • 출력 길이 제한

  • 낮은 temperature 설정

# Limit cost of complete
complete(prompt=prompt, 
         model='llama3.1-8b', 
         options={
            'max_tokens':120,

'temperature':0})
Snowflake에서 시작하는 생성형 AI

Cortex 모범 사례

  • 모델을 효과적으로 체이닝
# 하위 함수가 여러 개면 먼저 요약
summarize()
text_classify()
complete()
translate()
  • 로깅
  • 캐싱
  • 배치 파이프라인
Snowflake에서 시작하는 생성형 AI

연습해 봅시다!

Snowflake에서 시작하는 생성형 AI

Preparing Video For Download...